内容控件上的绑定不会更新数据
本文关键字:更新 数据 绑定 控件 | 更新日期: 2023-09-27 18:30:18
我有代码:
<TextBox Width="200" Text="{Binding Value}"></TextBox>
哪个有效。但是,"值"可以是不同的类型。因此,如果我有一个布尔值,我想显示一个复选框。我把它重写如下,这有点有效:
<ContentControl Content="{Binding Value}">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type sys:Boolean}">
<CheckBox IsChecked="{Binding Path=.}"></CheckBox>
</DataTemplate>
<DataTemplate DataType="{x:Type sys:Double}">
<TextBox Width="200" Text="{Binding Path=.}"></TextBox>
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
但是现在该属性不像以前那样更新。我尝试设置模式=双向,但它仍然不起作用。
编辑
当我只有文本框时,它工作得很好,编辑文本框的文本更新了模型。但是,当我尝试使用第二个代码(ContentControl)执行此操作时,它不起作用。
法典
我正在使用带有绑定的 Mvvm-light togheter。"值"绑定到属性的实例
[JsonObject]
public class Property<T> : INotifyPropertyChanged
{
[JsonProperty]
public String name;
public Property(String name, T value)
{
this._value = value;
this.name = name;
}
[JsonIgnore]
public T Value {
get { return _value; }
set {
_value = value;
hot = true;
NotifyPropertyChanged("Value");
}
}
[JsonProperty(PropertyName = "value")]
private T _value;
[JsonIgnore]
public String Name { get { return name; } set { name = value; } }
[JsonProperty]
public bool hot = false;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
您应该实现 INotifyPropertyChanged 接口以跟踪属性更改。我相信一切都很好。
这对我有用:
public partial class MainWindow : Window, INotifyPropertyChanged
{
private object value;
public MainWindow()
{
InitializeComponent();
Loaded += MainWindow_Loaded;
DataContext = this;
}
public object Value
{
get { return value; }
set
{
this.value = value;
NotifyPropertyChanged("Value");
}
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Value = true;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}