Windows Phone 8 アプリを作成しています。内容が非同期的に更新される UserControl があります。私のモデルは INotifyPropertyChanged を実装しています。モデルの値を更新すると、TextBox コントロールに反映されますが、UserControl のコンテンツには反映されません。パズルのどの部分が欠けていますか、それとも単に不可能ですか? これが私の再生シナリオです。
アプリページ:
<phone:PhoneApplicationPage x:Class="BindingTest.MainPage">
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Click="Button_Click" Content="Click" HorizontalAlignment="Left" Margin="147,32,0,0" VerticalAlignment="Top"/>
<TextBlock HorizontalAlignment="Left" Margin="69,219,0,0" TextWrapping="Wrap" Text="{Binding Bar}" VerticalAlignment="Top" Height="69" Width="270"/>
<app:MyControl x:Name="Snafu" HorizontalAlignment="Left" Margin="69,319,0,0" Title="{Binding Bar}" VerticalAlignment="Top" Width="289"/>
</Grid>
</phone:PhoneApplicationPage>
これは、モデル クラス (Foo) のコード ビハインドです。
public partial class MainPage : PhoneApplicationPage
{
Foo foo;
// Constructor
public MainPage()
{
InitializeComponent();
foo = new Foo();
ContentPanel.DataContext = foo;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
foo.Bar = "Gnorf";
}
}
public class Foo : INotifyPropertyChanged
{
string bar;
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string name)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name));
}
public Foo()
{
Bar = "Welcome";
}
public string Bar
{
get
{
return bar;
}
set
{
bar = value;
OnPropertyChanged("Bar");
}
}
}
ユーザー コントロール xaml
<UserControl x:Class="BindingTest.MyControl">
<TextBox x:Name="LayoutRoot" Background="#FF9090C0"/>
</UserControl>
そして、UserControl のコード ビハインド
public partial class MyControl : UserControl
{
public MyControl()
{
InitializeComponent();
}
public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(MyControl), new PropertyMetadata("", OnTitleChanged));
static void OnTitleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MyControl c = (MyControl)d;
c.Title = e.NewValue as String;
}
public string Title
{
get
{
return (string)GetValue(TitleProperty);
}
set
{
SetValue(TitleProperty, value);
LayoutRoot.Text = value;
}
}
}
この例を実行すると、UserControl TextBox に Welcome が含まれます。ボタンをクリックすると、通常の TextBox が Gnorf に更新されますが、UserControl にはまだ Welcome が表示されます。
また、UserControl にのみバインドすると、set_DataContext への呼び出しが返されたときに PropertyChanged イベント ハンドラーが null になることもわかりました。DataBinding インフラストラクチャは、UserControl へのバインディングが、通常の一方向バインディングではなく、1 回限りのバインディングであると推測しているようです。何か案は?