参数化 ControlTemplate 中使用的 ValueConverter 的好方法是什么?

发布于 2024-08-04 18:07:40 字数 769 浏览 2 评论 0原文

我正在开发的模板化控件使用如下所示的 ValueConverter:

<ListBox>
   <ListBox.Resources>
      <Controls:CodeDescriptionValueConverter x:Key="CodeDescriptionValueConverter"/>
   </ListBox.Resources>
   <ListBox.ItemTemplate>
      <DataTemplate>
         <TextBlock Text="{Binding Converter={StaticResource CodeDescriptionValueConverter}"/>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

这是我在 generic.xaml 中提供的默认外观。当我使用此控件时,我希望将不同的格式字符串传递到转换器中。有没有办法在不提供完整的 ControlTemplate 的情况下实现这一点?

我的第一个想法是我可以将 ConverterParameter 与 TemplateBinding 一起使用到控件上的属性,但我发现 ConverterParameters 无法绑定到。另一种选择可能是从 ConvertTo 方法访问该控件,然后选取该属性。我不知道该怎么做。任何可以消除每次使用控件时完全重新模板化控件的需要的选项都会很有帮助(它有很多 Xaml)。

A templated control I'm working on uses a ValueConverter like so:

<ListBox>
   <ListBox.Resources>
      <Controls:CodeDescriptionValueConverter x:Key="CodeDescriptionValueConverter"/>
   </ListBox.Resources>
   <ListBox.ItemTemplate>
      <DataTemplate>
         <TextBlock Text="{Binding Converter={StaticResource CodeDescriptionValueConverter}"/>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

This is the default look that I supply in generic.xaml. When I use this control I'll want to pass different format strings into the converter. Is there a way to make that happen without providing the full ControlTemplate?

My first thought was that I could use ConverterParameter with a TemplateBinding to a property on the control, but I discovered that ConverterParameters can't be bound to. Another option could be to get access to the control from the ConvertTo method, then pick off that property. I'm not sure how to do that. Any options that would eliminate the need to completely re-template the control each time I use it would be helpful (it's a lot of Xaml).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

顾冷 2024-08-11 18:07:40

在这些情况下,我通常会执行以下两种操作之一:

1) 绑定到一个对象,该对象可以访问要绑定到格式字符串的属性。在转换器中,您将可以访问属性和格式字符串。

2) 将格式字符串和格式化文本的属性添加到数据对象/视图模型/等中。然后绑定到格式化文本属性。假设您正在使用 INotifyPropertyChanged,请记住,每当您更改文本或格式字符串属性时,您都需要触发格式化文本属性的 propertychanged 事件

In these situations, I generally do one of two things:

1) Bind to an object that has access to both the property you want to bind to the format string. In the the converter you will then have access to both the property and the format string.

2) Add properties to your data object/viewmodel/etc for the format string and the formatted text. Then bind to the formatted text properties. Assuming that you are using INotifyPropertyChanged, keep in mind that you will need to fire the propertychanged event for the formatted text property whenever you change the text or format string properties

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文