绑定更新问题

Mak*_*aku 2 c# silverlight binding windows-phone-7

绑定属性更改时,我遇到绑定更新问题.看下面的代码.我将在以下示例中解释我的问题.

public class SettingsControl : INotifyPropertyChanged
    {

        string _value = "test";

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

        public SettingsControl() { }


     public string Value
        {
            get { return _value; }
            set { _value = value; OnPropertyChanged("Value"); }
        }
    }

<local:SettingsControl x:Key="Settings"></local:SettingsControl>

<TextBox Height="72" Text="{Binding Value, Mode=TwoWay, Source={StaticResource Settings} }"/>
<TextBlock Text="{Binding Value, Mode=OneWay, Source={StaticResource Settings} }" VerticalAlignment="Top" Width="135" />
<Button Height="100" Click="button1_Click" />
Run Code Online (Sandbox Code Playgroud)

和代码背后:

private void button1_Click(object sender, RoutedEventArgs e)
    {
        SettingsControl settings = new SettingsControl();
        settings.Value = "new value";
    }
Run Code Online (Sandbox Code Playgroud)

现在,当我改变文本时,TextBox一切正常.新文本显示在TextBlock.但是如果我在代码中设置新文本就settings.Value没有任何反应.

我想以改做什么settings.Value代码,影响TextPropertyTextBlock.

编辑:下面的解决方案为那些与我有同样问题的人:

    SettingsControl settings = (SettingsControl)this.Resources["Settings"];
    settings.Value = "new value";
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 5

在您的代码中,您将在新实例上设置值,而不是在正在使用的实例上.

尝试将代码更改为:

private void button1_Click(object sender, RoutedEventArgs e)
{
    // Set the Value on "this"
    this.Value = "new value";
}
Run Code Online (Sandbox Code Playgroud)

话虽如此,"控制"上的属性通常通过创建依赖属性来处理,而不是通过INotifyPropertyChanged.这允许在XAML中正确设置和使用它们,并在更多场景中完全参与绑定.