[英]Data Binding in WPF User Controls
我正在為幾個窗口共享的一系列控件創建一個UserControl。 其中一個控件是Label,它根據“協議編號”顯示其他一些過程的流程。
我正在嘗試使用此Label提供DataBinding,因此Window會在協議編號變量更改時自動反映進程的狀態。
這是用戶控件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>
這就是Code-Behind:
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的值。
我看過這個例子
如果你查看輸出窗口,你應該看到綁定異常。
您遇到的問題如下:在您的usercontrol中,您將標簽綁定到usercontrol的DP ProtocolNumber而不是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>
編輯:要清除一些內容,如果更改MainWindow中的綁定,則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
的聲明,使用RelativeSource
或ElementName
綁定來代替。
如果您沒有指定綁定的RelativeSource
,請嘗試在構造函數中設置DataContext
:
public Window1()
{
Number= 15;
DataContext = this;
InitializeComponent();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.