当开始使用WPF UserControls时,我发现有几种方法可以将UserControl的内容绑定到其属性之一。
以下是我的控件示例C#代码:
在XAML中,可视树的根DataContext被设置为UserControl。
构造函数中将可视树根的DataContext设置为UserControl
这是构造函数:
然而,如果UserControl的用户想要将其属性绑定到其他绑定源,则此方法无法实现。该UserControl需要从其父级继承DataContext才能使其正常工作。通过上述所示的重写,绑定将无法找到其源。
我的最后几个问题:
以下是我的控件示例C#代码:
public sealed partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
}
public static readonly DependencyProperty TheTextProperty =
DependencyProperty.Register("TheText",
typeof (string),
typeof(MyUserControl),
new FrameworkPropertyMetadata(0,
FrameworkPropertyMetadataOptions.
BindsTwoWayByDefault)
);
public string TheText
{
get { return (string)GetValue(TheTextProperty); }
set { SetValue(TheTextProperty, value); }
}
}
以下是我发现的将内容绑定到此属性的不同方法:
使用RelativeSource/AncestorType进行绑定的内容
<UserControl x:Class="MyUserControl"
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">
<StackPanel>
<TextBox Text="{Binding TheText,
RelativeSource={RelativeSource
AncestorType={x:Type UserControl}}}" />
</StackPanel>
</UserControl>
在XAML中,可视树的根DataContext被设置为UserControl。
<UserControl x:Class="MyUserControl"
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">
<StackPanel DataContext="{Binding
RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}">
<TextBox Text="{Binding TheText}" />
</StackPanel>
</UserControl>
构造函数中将可视树根的DataContext设置为UserControl
<UserControl x:Class="MyUserControl"
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">
<StackPanel x:Name="VisualTreeRoot">
<TextBox Text="{Binding TheText}" />
</StackPanel>
</UserControl>
这是构造函数:
public MyUserControl()
{
InitializeComponent();
VisualTreeRoot.DataContext = this;
}
最后但并非最不重要:针对WPF中新手编程UserControls的警告
第一次想要将UserControl的内容绑定到其属性之一时,我认为“嘿,让我们直接将UserControl的DataContext设置为自身”:
<UserControl x:Class="MyUserControl"
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"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
或者:
public MyUserControl()
{
InitializeComponent();
this.DataContext = this;
}
然而,如果UserControl的用户想要将其属性绑定到其他绑定源,则此方法无法实现。该UserControl需要从其父级继承DataContext才能使其正常工作。通过上述所示的重写,绑定将无法找到其源。
我的最后几个问题:
- 每种方法的优缺点是什么?
- 应该在什么情况下使用哪种方法?
- 还有更多的方法吗?