如何基于当前行的值在DataGridTemplateColumn DataTemplate中设置按钮可见性

时间:2018-08-16 13:52:43

标签: wpf mvvm

我正在尝试添加样式触发器,以基于视图模型上的“状态”属性设置“快速更改”按钮的可见性。如果State ==“ Released”,则显示;如果State!=“ Released”,则隐藏。我也尝试使用转换器执行此操作,但是在任何一种情况下,我都很难获得绑定以指向该行的viewmodel作为datacontext。

            <DataGrid.Columns>
            <DataGridTemplateColumn Header="Commands">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal" 
                                    DataContext="{Binding Path=DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}">
                            <Button Margin="0,0,3,0" 
                                    Command="{Binding OpenCommand}" 
                                    Content="Open"/>
                            <Button Margin="0,0,3,0" 
                                    Command="{Binding QuickChangeCommand}" 
                                    Content="Quick Chg"/>
                            <Button Margin="0,0,0,0" 
                                    Command="{Binding RevPartCommand}" 
                                    Content="Rev Part"/>
                        </StackPanel>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTextColumn Binding="{Binding Name}" Header="File Name"/>
            <DataGridTextColumn Binding="{Binding Rev}" Header="Rev"/>
            <DataGridTextColumn Binding="{Binding State}" Header="State"/>
            <DataGridCheckBoxColumn Binding="{Binding CheckedOut}" Header="Ckd Out"/>
            <DataGridTextColumn Binding="{Binding CheckedOutBy}" Header="Ckd Out By"/>
        </DataGrid.Columns>

1 个答案:

答案 0 :(得分:0)

尝试一下:

<Button Margin="0,0,3,0" 
        Command="{Binding QuickChangeCommand}" 
        Content="Quick Chg">
    <Button.Style>
        <Style TargetType="Button">
            <Setter Property="Visibility" Value="Collapsed" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding DataContext.State, RelativeSource={RelativeSource AncestorType=DataGrid}}" Value="Released">
                    <Setter Property="Visibility" Value="Visible" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

如果AncestorType属性是DataGridRow中数据对象的属性,则可以将State更改为DataGrid