WPF用户控件中的数据绑定

我正在为几个窗口共享的一系列控件创build一个UserControl。 其中一个控件是一个标签,用“协议号码”来表示一些其他进程的stream程。

我试图提供这个标签的DataBinding,所以窗口会自动反映进程的状态,因为协议号variables的变化。

这是用户控件XAML:

<UserControl Name="MainOptionsPanel" x:Class="ExperienceMainControls.MainControls" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" DataContext="{Binding RelativeSource={RelativeSource Self}}" > <Label Height="Auto" Name="numberLabel">Protocol:</Label> <Label Content="{Binding Path=ProtocolNumber}" Name="protocolNumberLabel"/> (...) </UserControl> 

这是代码隐藏:

 public partial class MainControls { public MainControls() { InitializeComponent(); } public int ProtocolNumber { get { return (int)GetValue(ProtocolNumberProperty); } set { SetValue(ProtocolNumberProperty, value); } } public static DependencyProperty ProtocolNumberProperty = DependencyProperty.Register("ProtocolNumber", typeof(int), typeof(MainControls)); } 

这似乎是工作的,因为如果在构造函数中我将ProtocolNumber设置为任意值,它将反映在用户控件中。

但是,在最终窗口中使用此用户控件时,数据绑定会中断。

XAML:

 <Window x:Class="UserControlTesting.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:expControl="clr-namespace:ExperienceMainControls;assembly=ExperienceMainControls" DataContext="{Binding RelativeSource={RelativeSource Self}}" > <StackPanel> <expControl:MainControls ProtocolNumber="{Binding Path=Number, Mode=TwoWay}" /> </StackPanel> </Window> 

代码隐藏窗口:

 public partial class Window1 : Window { public Window1() { Number= 15; InitializeComponent(); } public int Number { get; set; } } 

这将协议编号设置为零,忽略设置为数字的值。

我读过例子

如果你看看你的输出窗口,你应该看到绑定exception。

您遇到的问题如下:在您的用户控件中,将标签绑定到您的usercontrol的DP协议编号而不是DataContext ,因此您必须将元素名称添加到绑定中。

 <UserControl Name="MainOptionsPanel" x:Class="ExperienceMainControls.MainControls" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="uc" > <Label Height="Auto" Name="numberLabel">Protocol:</Label> <Label Content="{Binding Path=ProtocolNumber, ElementName=uc}" Name="protocolNumberLabel"/> (...) </UserControl> 

编辑:清除一些事情,你的用户控件也可以工作,如果你改变你的主窗口中的绑定。 但您必须使用RelativeSource绑定到MainWindow的DataContext。

  <expControl:MainControls ProtocolNumber="{Binding Path=Number, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" /> 

你有什么作用:

 <expControl:MainControls DataContext="{Binding RelativeSource={RelativeSource Self}}" ProtocolNumber="{Binding Path=Number, Mode=TwoWay}"/> 

=>不要将DataContext设置为UserControl声明,而是使用RelativeSourceElementName绑定。

如果您没有指定绑定的RelativeSource ,请尝试在构造函数中设置DataContext

  public Window1() { Number= 15; DataContext = this; InitializeComponent(); }