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

查看:996
本文介绍了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.

我的下一个想法是创建一个值转换器,并在上ConverterParameter通过FormatString属性的价值,但我遇到了同样的问题 - 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;更具体地,在一个文本框

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

我想preFER让XAML做的工作对我,所以我能避免与code-后面玩耍。我使用的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.

谢谢!

推荐答案

一个方法可能是创建一个继承文本框,并在该类创建自己的依赖属性的类即当设置为代表的StringFormat 。因此,而不是在你的XAML使用文本框您将使用继承文本框,并设置自己的依赖项属性的绑定。

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天全站免登陆