WPF 绑定和动态分配 StringFormat 属性 [英] WPF Binding and Dynamically Assigning StringFormat Property

查看:90
本文介绍了WPF 绑定和动态分配 StringFormat 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于多个 DataTemplate 元素生成的表单.DataTemplate 元素之一从如下所示的类中创建了一个 TextBox:

I have a form that is generated based on several DataTemplate elements. One of the DataTemplate elements creates a TextBox out of a class that looks like this:

public class MyTextBoxClass
{
   public object Value { get;set;}
   //other properties left out for brevity's sake
   public string FormatString { get;set;}
}

我需要一种方法将 FormatString 属性中的值绑定"到绑定的StringFormat"属性.到目前为止,我有:

I need a way to "bind" the value in the FormatString property to the "StringFormat" property of the binding. So far I have:

<DataTemplate DataType="{x:Type vm:MyTextBoxClass}">
 <TextBox Text="{Binding Path=Value, StringFormat={Binding Path=FormatString}" />
</DataTemplate>

但是,由于 StringFormat 不是依赖属性,我无法绑定到它.

However, since StringFormat isn't a dependency property, I cannot bind to it.

我的下一个想法是创建一个值转换器并将 FormatString 属性的值传递给 ConverterParameter,但我遇到了同样的问题 -- ConverterParameter 不是 DependencyProperty.

My next thought was to create a value converter and pass the FormatString property's value in on the ConverterParameter, but I ran into the same problem -- ConverterParameter isn't a DependencyProperty.

所以,现在我转向你,所以.如何动态设置绑定的 StringFormat;更具体地说,在 TextBox 上?

So, now I turn to you, SO. How do I dynamically set the StringFormat of a binding; more specifically, on a TextBox?

我更愿意让 XAML 为我完成工作,这样我就可以避免使用代码隐藏.我正在使用 MVVM 模式,并希望尽可能保持视图模型和视图之间的界限不模糊.

I would prefer to let XAML do the work for me so I can avoid playing with code-behind. I'm using the MVVM pattern and would like to keep the boundaries between view-model and view as un-blurred as possible.

谢谢!

推荐答案

一种方法可能是创建一个继承 TextBox 的类,并在该类中创建您自己的依赖属性,委托给 StringFormat 设置时.因此,不是在 XAML 中使用 TextBox,您将使用继承的文本框并在绑定中设置您自己的依赖项属性.

One way may be to create a class that inherits TextBox and in that class create your own dependency property that delegates to StringFormat when set. So instead of using TextBox in your XAML you will use the inherited textbox and set your own dependency property in the binding.

这篇关于WPF 绑定和动态分配 StringFormat 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆