如何在样式而不是路径中设置转换器



我正在尝试为文本框创建一种样式,我希望能够在我的代码中使用。我的样式在 Text 属性的绑定中定义了一个转换器,但没有设置其路径,因为在我使用此样式的任何地方,我的绑定数据可能命名不同。

<Style x:Key="CustomTextBox" BasedOn="{StaticResource {x:Type TextBox}}"
    TargetType="{x:Type TextBox}">
    <Setter Property="Text">
        <Setter.Value>
            <Binding>
                <Binding.Converter>
                    <CustomTextBoxConverter/>
                </Binding.Converter>
            </Binding> 
        </Setter.Value>
    </Setter>
</Style>

然后自定义文本框将像这样使用:

<TextBox Height="28" Name="txtRate" Style="{StaticResource CustomTextBox}"
         MaxLength="5" Text="{Binding Path=BoundData}"/>

当我编写上面的代码时,我得到一个"双向绑定需要 Path 或 XPath"的解释。

我什至尝试创建一个在样式绑定中使用的附加属性以在样式中反映此值,但我也无法开始工作。请参阅下一页 :

<Converters:SomeConvertingFunction x:Key="CustomTextConverter"/>
<local:CustomAttachedProperties.ReflectedPath x:Key="ReflectedPath"/>
<Style x:Key="CustomTextBox" BasedOn="{StaticResource {x:Type TextBox}}"
    TargetType="{x:Type TextBox}">
    <Setter Property="Text">
        <Setter.Value>
            <Binding Path=ReflectedPath Converter=CustomTextConverter/>
        </Setter.Value>
    </Setter>
</Style>

在这样的页面中使用:

<TextBox Height="28" Name="txtRate" Style="{StaticResource CustomTextBox}"
         MaxLength="5" CustomAttachedProperty="contextBoundDataAsString"/>

附加属性的代码是:

Public Class CustomAttachedProperties
    Public Shared ReadOnly ReflectedPathProperty As DependencyProperty = 
        DependencyProperty.RegisterAttached("ReflectedPath", GetType(String),
        GetType(CustomAttachedProperties))
    Public Shared Sub SetReflectedPath(element As UIElement, value As String)
        element.SetValue(ReflectedPathProperty, value)
    End Sub
    Public Shared Function GetReflectedPath(element As UIElement) As String
        Return TryCast(element.GetValue(ReflectedPathProperty), String)
    End Function
End Class

当我尝试使用上面的代码时,它可以很好地编译,但它似乎没有在我的 XAML 上做任何事情,就像它可能正在创建 CustomAttachedProperty 的不同实例一样。

很抱歉提出这个问题,但我认为创建具有自己的默认 WPF 转换器的自定义控件应该很容易......我很困惑!

您可以创建一个非常简单的UserControl

<UserControl x:Class="namespace.MyCustomConverterTextBox">
    <TextBlock Text="{Binding Text, Converter={StaticResource yourconverter}}"/>
</UserControl>

然后在代码隐藏中将Text声明为DependencyProperty

public partial class MyCustomConverterTextBox : UserControl
{
    public string Text {
        get{return (string) GetValue(TextProperty);} 
        set{SetValue(TextProperty, value);}
    }
    public static readonly DependencyProperty TextProperty = 
        DependencyProperty.Register("Text", typeof(string), typeof(MyCustomConverterBox));
 }

这应该足以让你在 xaml 中使用它:

<local:MyCustomConverterTextBox Text="{Binding YourBinding}" />

我没有运行这段代码,所以可能有拼写错误,但它应该足以让你知道如何去做。

在我看来,最好的方法是创建一个继承自 TextBox 的新类,然后覆盖 Text 属性的PropertyMetadata,让自己有机会在Coerce回调中更改值。

相关内容

最新更新