我如何创建一个复杂的类属性,可以绑定到WPF TextBlock?



我有一个具有复杂属性的类,它绑定到我的UI控件。类可以随意转换为字符串或从字符串转换为字符串。我如何得到类绑定到一个文本框正确?

[TypeConverter(typeof(LatLongTypeConverter))]
public class LatLong : IComparable, IXmlSerializable
{
.
.
.
public override string ToString() {...}
public static implicit operator LatLong(string L) {...}
public static explicit operator string(LatLong L) {...}
public class LatLongTypeConverter : TypeConverter
{
.
.
.
}
}
public class City : INotifyPropertyChanged
{
private string _Name = "Chicago";
private LatLong _Location = "41.52N 87.37W";
public string Name
{
get => _Name;
set { _Name = value; Notify(); }
}
public LatLong Location
{
get => _Location;
set { _Location = value; Notify(); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void Notify([System.Runtime.CompilerServices.CallerMemberName] string PropertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
}
}

XAML:

<TextBlock Text="{Binding Location}"/>

如何让TextBlock显示"41.52N 87.37W"不使用IValueConverter?目前,类型转换在代码中工作得很好,但是当绑定时,它只显示一个空白字段。

WPF只需要一个TextBlock文本绑定到一个字符串,任何比这更复杂的东西都需要直接绑定一个转换器。这就留下了两个选项,创建一个IValueConverter,它需要一个LatLong实例并返回一个字符串,例如调用其隐式转换,或者在你的代码后面/viewmodel/任何你绑定到。

这里我将展示一种非常简单的方法来实现第二个选项,通过添加一个额外的属性让WPF绑定到:
//New property for WPF to bind to, simply takes the full object and uses it's implicit string conversion
public string LocationString => (string)this.Location;
public LatLong Location
{
get => _Location;
//Here we notify changes of both properties, as one is calculated from the other
set { _Location = value; Notify(); Notify("LocationString"); }
}

然后简单地将绑定更改为XAML中的新属性:

<TextBlock Text="{Binding LocationString}"/>

最新更新