详细说明@Steven 你的答案,在你的 UserControl 中定义一个DependencyProperty。
定义DependencyProperty 允许更改通知触发控件更新。
在 UserControl 的代码隐藏中,您可以添加依赖属性。
public partial class MyUserControl : UserControl
{
public string TextBlockText
{
get { return (string)GetValue(TextBlockTextProperty); }
set { SetValue(TextBlockTextProperty, value); }
}
public static readonly DependencyProperty TextBlockTextProperty =
DependencyProperty.Register("TextBlockText", typeof(string), typeof(MyUserControl), new UIPropertyMetadata(""));
public MyUserControl()
{
InitializeComponent();
DataContext = this;
}
}
这会公开一个公共 DependencyProperty,您可以在 UserControl 的 XAML 中绑定到该 DependencyProperty。
<UserControl>
<TextBlock Text="{Binding Path=TextBlockText}" />
</UserControl>
现在您需要一种从 Window 控件设置该属性的方法。我将详细介绍您可以执行此操作的三种方式:
1.) 由于 TextBlockText 属性在 UserControl 上公开,我们可以直接在 XAML 中设置它,如下所示:
<Window x:Class="WpfApplication2.MainWindow"
xmlns:local="clr-namespace:WpfApplication2">
<local:MyUserControl TextBlockText="Text that you want to set.">
</local:MyUserControl>
</Window>
2.) 如果我们给 UserControl 一个名称,我们可以在 Window 代码隐藏中更改属性:
<Window x:Class="WpfApplication2.MainWindow"
xmlns:local="clr-namespace:WpfApplication2">
<local:MyUserControl Name="CoolUserControl">
</local:MyUserControl>
</Window>
-
CoolUserControl.TextBlockText = "Text that you want to set.";
3.) 或者最后您可以在 Window 的代码隐藏中创建另一个 DependencyProperty 并将其绑定到 UserControl 的依赖属性。这样,每当您更新属性时,Window 代码中的值UserControl 依赖属性也会发生变化。正如@Steven You 之前所说,这是更可取的选择,因为您背后的代码不需要了解任何控件。
public partial class MainWindow : Window
{
public string UserControlText
{
get { return (string)GetValue(UserControlTextProperty); }
set { SetValue(UserControlTextProperty, value); }
}
public static readonly DependencyProperty UserControlTextProperty =
DependencyProperty.Register("UserControlText", typeof(string), typeof(MainWindow), new UIPropertyMetadata(""));
public MainWindow()
{
InitializeComponent();
DataContext = this;
UserControlText = "Text that you want to set.";
}
}
并绑定到我们在 Window XAML 中的新 DependencyProperty:
<Window x:Class="WpfApplication2.MainWindow"
xmlns:local="clr-namespace:WpfApplication2">
<local:MyUserControl TextBlockText="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}, Mode=FindAncestor}, Path=UserControlText}"></local:MyUserControl>
</Window>
希望这会有所帮助!