【发布时间】:2016-02-14 07:07:10
【问题描述】:
我是 WPF 的新手,很想知道如何嵌套绑定 WPF 中的属性。我制作了一个示例应用程序以便更好地理解。请在下面找到以下场景。
工作代码:
UserControl1 >> 主窗口
创建了一个用户控件并将其包含在主窗口中。
UserControl1.xaml
<StackPanel>
<TextBox x:Name="text1" Text="{Binding MyTextUC1, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox />
</StackPanel>
UserControl1.xaml.cs
public UserControl1()
{
InitializeComponent();
this.DataContext = this;
}
public static readonly DependencyProperty MyTextUC1Property =
DependencyProperty.Register("MyTextUC1", typeof(string), typeof(UserControl1));
public string MyTextUC1
{
get { return (string)GetValue(MyTextUC1Property); }
set { SetValue(MyTextUC1Property, value); }
}
MainWindwo.xaml
<StackPanel>
<local:UserControl1 x:Name="text1"/>
<TextBlock Text="{Binding ElementName=text1, Path=MyTextUC1}" />
</StackPanel>
在运行此程序时,UserControl1 的 TextBox 中的文本更改会反映在 MainWindow 的 TextBlock 中。
不工作:
用户控件1 >> 用户控件2 >> 主窗口
创建了一个 UserControl(usercontrol1) 并将其包含在另一个 UserControl(usercontrol2) 中,然后将 UserControl2 包含在 mainWindow 中。
UserControl1.xaml & UserControl1.xaml.cs
//Same as Working Code
UserControl2.xaml
<Grid>
<local:UserControl1 x:Name="text2" MyTextUC1="{Binding MyTextUC2,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
UserControl2.xaml.cs
public UserControl2()
{
InitializeComponent();
this.DataContext = this;
}
public static readonly DependencyProperty MyTextUC2Property =
DependencyProperty.Register("MyTextUC2", typeof(string), typeof(UserControl2));
public string MyTextUC2
{
get { return (string)GetValue(MyTextUC2Property); }
set { SetValue(MyTextUC2Property, value); }
}
MainWindwo.xaml
<StackPanel>
<local:UserControl2 x:Name="text1"/> //UserControl2 contains UserControl1
<TextBlock Text="{Binding ElementName=text1, Path=MyTextUC2}" />
</StackPanel>
在运行此程序时,UserControl2 的 TextBox 中的文本更改未反映在 MainWindow 的 TextBlock 中。
我很确定这是 WPF 中的基本内容,我可能以错误的方式实现它。有人可以建议我哪里错了吗?提前致谢。
【问题讨论】:
标签: c# wpf data-binding dependency-properties