モデル(ウィンドウ/ユーザーコントロール)コードビハインドのプロパティにバインドする場合は、を設定する必要がありDataContext
ますXaml
。これを行う方法はいくつかありますが、最も簡単なのは、ウィンドウまたはユーザーコントロールに名前を付け、を使用してバインドすることElementName
です。
ウィンドウの例:
<Window x:Class="WpfApplication8.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="233" Width="143" Name="UI">
<Canvas DataContext="{Binding ElementName=UI}" > <!-- Set dataContext to Window -->
<Namespace:DeckControl Canvas.Left="50" Table="{Binding ElementName=Table}">
</Canvas>
</Window>
また、Xaml
テーブルが変更されたときに更新する場合は、コードビハインドで実装する必要があります。これにより、プロパティが変更されたことINotifyPropertyChanged
が通知されます。Xaml
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
}
private TableControl m_Table;
public TableControl Table
{
get { return m_Table; }
set { m_Table = value; NotifyPropertyChanged("Table"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
TableプロパティがDependancyPropertyでない場合は、バインドできるようにこれを変更する必要があります。
例:
public class DeckControl : UserControl
{
.......
// Using a DependencyProperty as the backing store for Table. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TableProperty =
DependencyProperty.Register("Table", typeof(TableControl), typeof(DeckControl), new UIPropertyMetadata(null));
public TableControl Table
{
get { return (TableControl)GetValue(TableProperty); }
set { SetValue(TableProperty, value); }
}
}
また、UserControlのスコープ外でバインドされているプロパティは、DependancyPropertyである必要があります。
例:
public partial class DeckControl : UserControl
{
public DeckControl()
{
InitializeComponent();
}
private int myVar;
public int MyProperty
{
get { return myVar; }
set { myVar = value; }
}
}
これは、スコープ内にある単純なプロパティである場合、ユーザーコントロール内にバインドされます。
<UserControl .....
d:DesignHeight="300" d:DesignWidth="300" Name="UI">
<TextBlock Text="{Binding MyProperty}" />
</UserControl>
これはUserControlの範囲外であるためバインドされません。ここでバインドするには、MyPropertyがDependancyPropertyである必要があります。
<Window ....
Title="MainWindow" Height="233" Width="143" Name="UI">
<Grid>
<local:DeckControl MyProperty="{Binding Width}" /> // Will not bind
</Grid>
</Window>
それが理にかなっていることを願っています:)