2

我正在构建一个 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 事件处理程序为空。DataBinding 基础结构似乎推断与我的 UserControl 的绑定是一次性绑定,而不是常规的单向绑定。有任何想法吗?

4

1 回答 1

0

尝试这个:-

 <app:UserControl1 x:Name="Snafu" Title="{Binding Bar,Mode=TwoWay}" />

我检查了它..这将工作.. :)

于 2013-07-25T13:22:01.827 回答