【发布时间】:2012-06-28 22:08:27
【问题描述】:
我正在为多个窗口共享的一系列控件创建一个 UserControl。其中一个控件是一个标签,它以“协议号”的形式显示其他一些流程的流程。
我正在尝试使用此标签提供 DataBinding,以便窗口在协议编号变量更改时自动反映进程的状态。
这是用户控件 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; }
}
这会将协议编号设置为零,忽略设置为 Number 的值。
我读过例子
【问题讨论】:
-
在您的输出窗口中,您将看到一个绑定错误,例如对象 MainOptionsPanel 没有属性编号 - 这是真的。只需将您的用户控件 xaml 更改为我的答案。
标签: c# wpf xaml data-binding user-controls