【发布时间】:2020-08-03 16:13:42
【问题描述】:
我有一个带有双向绑定的文本框,但它给出了TargetException 错误。数据未加载到 TextBox 中,当我输入它时,我收到此错误:
System.Windows.Data Error: 8 : Cannot save value from target back to source. BindingExpression:Path=(local:Config.eventDateFormat); DataItem='String' (HashCode=-247125614); target element is 'TextBox' (Name='TXTB_Settings_Event_AddDateToName'); target property is 'Text' (type 'String') TargetException:'System.Reflection.TargetException: Object does not match target type.
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)
at MS.Internal.Data.PropertyPathWorker.SetValue(Object item, Object value)
at System.Windows.Data.BindingExpression.UpdateSource(Object value)'
这是我的 XAML:
<TextBox x:Name="TXTB_Settings_Event_AddDateToName"
Text="{Binding (local:Config.eventDateFormat), Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
TextWrapping="Wrap" Margin="110,200,1012,492"/>
这是类和属性:
public class Config : INotifyPropertyChanged
{
private string _eventDateFormat = "MMM-dd-yy-";
public string eventDateFormat
{
get { return _eventDateFormat; }
set
{
if (value != _eventDateFormat)
{
_eventDateFormat = value;
OnPropertyChanged(nameof(eventDateFormat));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
我也试过这个:
private string _eventDateFormat = "MMM-dd-yy-";
public string eventDateFormat
{
get { return _eventDateFormat; }
set
{
if (value != _eventDateFormat)
{
_eventDateFormat = value;
Changed();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void Changed([CallerMemberName] string property = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
MainWindow 的数据上下文是:
this.DataContext = this;
我有一堆绑定到其他 UI 元素的可观察集合,所以我不能将 DataContext 更改为只是 Config。我尝试绑定到它们所在的网格,但无法编译。
当我的 Config 类是静态的时,我能够进行两种方式的绑定,而不是实现 INotifyPropertyChanged。然而,根据我的阅读,这个类不应该是静态的,因为它有时会更新。
不确定是否相关,我正在使用 MahApps Metro 2.0
使用 c# 4.6.1
【问题讨论】:
-
创建绑定时,括号中的属性名称是为附加属性指定的。您的 eventDateFormat 属性是普通属性。要绑定到它,您必须首先创建一个 Config 类型的实例。究竟如何——我不能说。你提供的代码不够看懂。
标签: c# wpf binding inotifypropertychanged