複数のウィンドウで共有される一連のコントロールの UserControl を作成しています。コントロールの 1 つは、「プロトコル番号」に関して他のプロセスの流れを示すラベルです。
このラベルで 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 に設定された値を無視して、Protocol Number がゼロに設定されます。
例を読んだ