WPF 绑定不接受任何更改
WPF bindings do not pick up any changes
在我的 WPF 应用程序中,我有一些属性已绑定到 XAML 对应项,但由于某些原因,当它们的值发生变化时不会设置。我已经实现了 INotifyPropertyChanged
接口并为此视图设置了 DataContext
,但它仍然没有接受任何更改。
对于此 ViewModel 中的其他属性,我有相同的模式,这些属性有效,而其他属性则无效。
这是我当前代码的一个片段:
视图模型
public class TestViewModel : INotifyPropertyChanged
{
private string testString;
public TestViewModel()
{
.....
this.RunCommand = new RelayCommand(this.RunAction);
}
public string TestString
{
get
{
return this.testString;
}
set
{
this.testString = value;
this.OnPropertyChanged("TestString");
}
}
private void RunAction()
{
.....
this.testString = "Running.";
}
}
查看
<StatusBarItem>
<TextBlock Text="{Binding Path=TestString, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" />
</StatusBarItem>
DataContext(在另一个 MainWindow
class 的代码隐藏中设置)
var testViewModel = SimpleIoc.Default.GetInstance<TestViewModel>();
var testWindow = new TestWindow() { DataContext = testViewModel };
testingWindow.Show();
如果有帮助,这是使用 MVVM-Light 在 classes 之间传递属性的多窗口应用程序的一部分。
我发现了问题。您只是在更新私有 属性 testString。但是您没有更新 属性 TestString,因此永远不会调用通知。
试试这个:
this.TestString = "Running";
您没有更改 TestString 的值,您正在分配一个命令来更改值但您似乎没有执行它。
this.RunCommand = new RelayCommand(this.RunAction);
将该命令绑定到某物或从某处手动执行它。
您还需要分配 属性 而不是字段
this.TestString = "Running.";
在我的 WPF 应用程序中,我有一些属性已绑定到 XAML 对应项,但由于某些原因,当它们的值发生变化时不会设置。我已经实现了 INotifyPropertyChanged
接口并为此视图设置了 DataContext
,但它仍然没有接受任何更改。
对于此 ViewModel 中的其他属性,我有相同的模式,这些属性有效,而其他属性则无效。
这是我当前代码的一个片段:
视图模型
public class TestViewModel : INotifyPropertyChanged
{
private string testString;
public TestViewModel()
{
.....
this.RunCommand = new RelayCommand(this.RunAction);
}
public string TestString
{
get
{
return this.testString;
}
set
{
this.testString = value;
this.OnPropertyChanged("TestString");
}
}
private void RunAction()
{
.....
this.testString = "Running.";
}
}
查看
<StatusBarItem>
<TextBlock Text="{Binding Path=TestString, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}" />
</StatusBarItem>
DataContext(在另一个 MainWindow
class 的代码隐藏中设置)
var testViewModel = SimpleIoc.Default.GetInstance<TestViewModel>();
var testWindow = new TestWindow() { DataContext = testViewModel };
testingWindow.Show();
如果有帮助,这是使用 MVVM-Light 在 classes 之间传递属性的多窗口应用程序的一部分。
我发现了问题。您只是在更新私有 属性 testString。但是您没有更新 属性 TestString,因此永远不会调用通知。
试试这个:
this.TestString = "Running";
您没有更改 TestString 的值,您正在分配一个命令来更改值但您似乎没有执行它。
this.RunCommand = new RelayCommand(this.RunAction);
将该命令绑定到某物或从某处手动执行它。
您还需要分配 属性 而不是字段
this.TestString = "Running.";