gpt4 book ai didi

c# - 如何在不更改 viewmodel 的属性 getter 的情况下在 XAML 中格式化字符串?

转载 作者:太空宇宙 更新时间:2023-11-03 23:32:28 25 4
gpt4 key购买 nike

我的应用程序中有以下界面:

public interface IContactMedium
{
string ContactString { get; set; }
string Type { get; set;}
bool IsValid();
}

此接口(interface)适用于代表某个人的某种联系方式的对象。它可以是电话、电子邮件等。ContactString 属性是实际的联系人数据(例如,对于电话,它是电话号码),Type 用于区分一个人拥有多个电话(对于电话,一个人可以拥有家庭电话、工作电话、手机等)IsValid 方法是每个人的验证机制不同类型的接触介质。

所以,假设我的应用程序中有两个对象 - EmailPhone - 都实现了接口(interface)。我将在应用程序中创建一个 UserControl,它包含一个管理此类对象列表的 UI。所以 View 模型看起来像这样:

public class ContactsCollectionViewModel<T> : ViewModelBase where T : class, IContactMedium
{
private ObservableCollection<T> _itemsCollection;

public ContactCollectionViewModel(ObservableCollection<T> items)
{
ItemsCollection = items;
}

public ObservableCollection<T> ItemsCollection
{
get { return _itemsCollection; }
set
{
if (_itemsCollection != value)
{
_itemsCollection = value;
OnPropertyChanged(() => ItemsCollection);
}
}
}
}

我想向 IContactMedium 接口(interface)添加另一个属性/方法,该属性/方法在 WPF 的绑定(bind)中使用时为 ContactString 属性提供正确的格式。这个想法是绑定(bind)到 ContactString 的文本框中的格式根据实际存储在集合中的具体对象而有所不同:

<TextBox x:Name="ContactString"
Text="{Binding ContactString, StringFormat=???}" />

我在网上搜索了解决方案,但找不到任何东西。我看到有人建议修改 ContactString 属性,以便 getter 返回格式化值。因此,例如,对于 Phone 对象,该属性将如下所示:

public string ContactString
{
get
{
return string.Format("({0}) {1}-{2}", _contactString.Substring(0,3), _contactString.Substring(4,3), _contactString.Substring(7,3));
}
set {
_contactString = value;
}
}

但是,这对我来说不是一个好的解决方案。该信息不仅由 UI 使用。它还会发送到应用程序的其他部分,包括需要原始格式电话号码的数据库:##########。

有没有办法为 XAML 提供格式化程序以在绑定(bind)的 StringFormat 属性中使用?格式可以由实现接口(interface)的对象指定吗?如果是,它需要是什么类型,我怎样才能使 XAML 中的 Binding 可以访问它?

最佳答案

Can the formatting be dictated by the object that implement the interface?

在 Xaml 中,可以提供与特定类关联的数据模板。

只需为模板中的结构提供绑定(bind)到目标属性的格式,如下所示:

<Grid>
<Grid.Resources>
<DataTemplate DataType="{x:Type c:Ship}">
<TextBlock Text="{Binding Path=Name, StringFormat=Ship: {0}}"
Foreground="Red" />
</DataTemplate>
<DataTemplate DataType="{x:Type c:Passage}">
<TextBlock Text="{Binding Path=Name, StringFormat=Passage: {0}}"
Foreground="Blue" />
</DataTemplate>
</Grid.Resources>
<ListBox Name="myListBox"
Height="300"
Width="200"
ItemsSource="{Binding OBSCollection}">
</ListBox>
</Grid>

所以对于我的集合,其中 ShipPassage 的类实例都遵守 ITreeEntity:

 public ObservableCollection<ITreeEntity> OBSCollection ...

当绑定(bind)创建一个列表时,绑定(bind)具有特定的字符串格式:

enter image description here

注意在设置数据时先添加船只,然后添加段落。无论如何,Xaml 不会对它们进行排序。


需要在复合集合中的一个 ListBox 中列出不同类型的对象?在这里查看我的答案:

关于c# - 如何在不更改 viewmodel 的属性 getter 的情况下在 XAML 中格式化字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31665409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com