c# - WPF 在 Style 中设置 ColumnDefinition.Width 不起作用?

标签 c# wpf xaml

我正在尝试将 ColumnDefinitionWidth"Auto" 更改为 "*" 使用应用于我的 ColumnDefinitionStyle。在我的 Style 中,有一个 DataTrigger 绑定(bind)到名为 CheckMeCheckBoxIsChecked 属性>。

示例代码:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="Auto">
            <ColumnDefinition.Style>
                <Style TargetType="ColumnDefinition">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ElementName=CheckMe,Path=IsChecked}" Value="True">
                            <Setter Property="Width" Value="*" />
                            <Setter Property="MinWidth" Value="300" />
                        </DataTrigger>
                        <DataTrigger Binding="{Binding ElementName=CheckMe,Path=IsChecked}" Value="False">
                            <Setter Property="Width" Value="Auto" />
                            <Setter Property="MinWidth" Value="50" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ColumnDefinition.Style>
        </ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Border Background="Green">
        <CheckBox x:Name="CheckMe" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
            <TextBlock Text="Use * width" />
        </CheckBox>
    </Border>
    <StackPanel Grid.Column="1">
        <TextBlock Text="Second column" />
    </StackPanel>
</Grid>

在我的示例代码中,我还设置了 MinWidth 属性,该属性确实起作用。

这可能吗?也许改用自定义 AttachedProperty

最佳答案

尝试删除显式宽度声明

<ColumnDefinition Width="Auto">

并在样式中设置

<ColumnDefinition>
     <ColumnDefinition.Style>
         <Style TargetType="ColumnDefinition">
             <Setter Property="ColumnDefinition.Width" Value="Auto"/>

If you want to switch some property value with triggers based on some condition, you need to set those properties' default value in the style itself otherwise no matter what values you set in your setter the properties' value will always be overridden by the local values of those properties due to dependency property value precedence.

关于c# - WPF 在 Style 中设置 ColumnDefinition.Width 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49065820/

相关文章:

WPF圆形奇怪的边框

c# - 将 WPF Button CommandParameter 绑定(bind)到 DataTemplate 中的 Button 本身

C# WPF - 如何在运行后自动刷新 UI

c# - 如何自动应用 generic.xaml 中的数据模板?

c# - Xamarin Master Detail 句柄泛型

c# - Tha xaml 图形在页面中有多个位置时消失

c# - 捕获异常并在我的自定义错误处理程序中处理

wpf - 在 wpf 中以编程方式添加主机控件时,命令绑定(bind)不起作用

.net - 多重触发的否定或非条件元素

c# - 递归如何打印列表的总和