首页 > 解决方案 > 基于另一个使用数据模板的样式创建样式

问题描述

我有一个使用 TextBoxes 的 ListBox 样式,定义如下:

       <Style x:Key="MyListBoxStyle" TargetType="ListBox">
        <Setter Property="Background" Value="LightGray"/>
        <Setter Property="BorderThickness" Value="2"/>
        <Setter Property="BorderBrush" Value="Black"/>
        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBox Text="{Binding Mode=OneWay}" Background="LightGray"/>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>

我使用这种样式为一些 ListBox 显示只读数据。

我还拥有一组 ListBoxes,我希望能够在其中单击其中一个 TextBoxes,然后执行一些操作。所以我想做的是在 TextBox 上附加一个 Click 事件。理想情况下,我想利用上述样式而不必重新输入所有内容,只需添加一个添加事件绑定的新样式。你会怎么做?

标签: wpf

解决方案


Style.BaseOn

<Style x:Key="MyListBoxStyle" TargetType="ListBox">
    <Setter Property="Background" Value="LightGray"/>
    <Setter Property="BorderThickness" Value="2"/>
    <Setter Property="BorderBrush" Value="Black"/>
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBox Text="{Binding Mode=OneWay}" Background="LightGray"/>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>
<Style x:Key="MyListBoxStyle2" BasedOn="{StaticResource MyListBoxStyle}" TargetType="ListBox">
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBox Text="{Binding Mode=OneWay}" Background="LightGray" GotFocus="TextBox_GotFocus"/>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

推荐阅读