How to assign a datatemplate to textbox wpf

后端 未结 1 1581
逝去的感伤
逝去的感伤 2021-01-19 07:27

TextBox is supposed to show masked dollar amount for certain access privileges. I created a converter class(inheriting from IValueConverter) to handle masking by implementi

相关标签:
1条回答
  • 2021-01-19 08:17

    You can use a ContentControl to display your DataTemplate. Another idea, which I prefer in this case, is to use styles. Below code shows hot to do both.

    <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>
    
    0 讨论(0)
提交回复
热议问题