您必须在您的用户控件中创建 DependencyProperty,它将用于绑定复选框和描述。像这样的东西
public partial class UserControl1 : UserControl
{
public bool IsChecked
{
get { return (bool)GetValue(IsCheckedProperty); }
set { SetValue(IsCheckedProperty, value); }
}
// Using a DependencyProperty as the backing store for IsChecked. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsCheckedProperty =
DependencyProperty.Register("IsChecked", typeof(bool), typeof(UserControl1), new UIPropertyMetadata(false));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new UIPropertyMetadata(string.Empty));
public UserControl1()
{
InitializeComponent();
}
}
您的用户控件 xaml 如下所示..
<UserControl x:Class="WpfApplication1.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" Name="Root">
<StackPanel>
<CheckBox IsChecked="{Binding IsChecked,ElementName=Root}"></CheckBox>
<TextBlock Text="{Binding Text,ElementName=Root}"></TextBlock>
</StackPanel>
</UserControl>
如果您发现我已将复选框和文本框绑定到我在用户控件中创建的依赖属性。
当你使用用户控件时,你可以绑定 DependencyProperty
<Grid>
<local:UserControl1 IsChecked="{Binding yourBinding}" Text="{Binding yourBinding}"/>
</Grid>