如何将数据模板分配给文本框 wpf

use*_*623 4 wpf textbox

TextBox 应该显示某些访问权限的隐藏金额。我创建了一个转换器类(从 IValueConverter 继承)来通过实现 convert 方法来处理屏蔽。

public object Convert(object value, Type targetType, object parameter, 
                  CultureInfo culture)
Run Code Online (Sandbox Code Playgroud)

如果需要屏蔽,则第三个参数为 true,否则为 false。

像这样调用:

CurrencyCOnverter converter = new CurrencyConverter();

this._textbox1.Text = converter.Convert(Amount, typeof(string), !this.IsSuperUser,
                          CurrentCulture).ToString();
Run Code Online (Sandbox Code Playgroud)

我在 UI 上有大约 12 个文本框。我没有在 12 个地方这样做,而是在 Resource 字典中定义了 DataTemplates,如下所示:

<DataTemplate x:Key="MaskNormalBackgroundTbx">

 <TextBlock TextAlignment="Right" VerticalAlignment="Center"
            TextWrapping="WrapWithOverflow" 
            Text="{Binding "Amount" 
                   Converter={StaticResource CurrencyDisplayConverter}, 
                   ConverterParameter=true}" />    
</DataTemplate>

 <DataTemplate x:Key="NoMaskNormalBackgroundTbx">

 <TextBlock TextAlignment="Right" VerticalAlignment="Center" 
            TextWrapping="WrapWithOverflow" 
            Text="{Binding "Amount" 
                   Converter={StaticResource CurrencyDisplayConverter}, 
                   ConverterParameter=false}" />    
 </DataTemplate>
Run Code Online (Sandbox Code Playgroud)

我的问题:有没有一种方法可以通过创建自定义文本框来将此模板分配给文本框,就像我们为 ListBox 分配数据模板一样?

谢谢,

梅根。

Wal*_*mer 5

您可以使用 ContentControl 来显示您的 DataTemplate。在这种情况下,我更喜欢的另一个想法是使用样式。下面的代码显示了两者都可以做的热点。

<Window x:Class="Test.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Test="clr-namespace:Test"
    Height="300" Width="300">

    <Window.Resources>

        <Test:CurrencyDisplayConverter x:Key="CurrencyDisplayConverter" />

        <DataTemplate x:Key="MaskNormalBackgroundTbxDT">
            <TextBlock TextAlignment="Right" VerticalAlignment="Center" 
            TextWrapping="WrapWithOverflow"  
            Text="{Binding Converter={StaticResource CurrencyDisplayConverter}, ConverterParameter=true}" />
        </DataTemplate>

        <Style x:Key="MaskNormalBackgroundTbxStyle" TargetType="TextBlock">
            <Setter Property="TextAlignment" Value="Right" />
            <Setter Property="VerticalAlignment" Value="Center" />
            <Setter Property="TextWrapping" Value="WrapWithOverflow" />
            <Setter Property="Text" Value="{Binding Path=Amount, Converter={StaticResource CurrencyDisplayConverter}, ConverterParameter=true}" />
        </Style>

    </Window.Resources>
    <StackPanel>

        <ContentControl
            Content="{Binding Path=Amount}" 
            ContentTemplate="{StaticResource MaskNormalBackgroundTbxDT}" />

        <TextBlock 
            Style="{StaticResource MaskNormalBackgroundTbxStyle}" />

    </StackPanel>

</Window>
Run Code Online (Sandbox Code Playgroud)