WPF: How to set bool to true from DataTemplate for Button?

血红的双手。 提交于 2019-12-02 08:59:46

why not use ToggleButton and bind IsChecked property to IsToDelete property of a viewModel?

simplified example with ItemsControl

<ItemsControl>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <ToggleButton Content="X" IsChecked="{Binding Path=IsToDelete}"/>
                <Border Width="100"                                
                        Background="MediumPurple" 
                        Margin="5">

                    <Border.Style>
                        <Style TargetType="Border">
                            <Setter Property="Visibility" Value="Visible"/>
                            <Style.Triggers>                                        
                                <DataTrigger Binding="{Binding Path=IsToDelete}" Value="True">
                                    <Setter Property="Visibility" Value="Collapsed"/>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </Border.Style>

                </Border>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>            
</ItemsControl>

You could use the Click eventhandler of the Button. Then you don't need any Commands.

private void bt_Delete_Click(object sender, RoutedEventArgs e)
{
    var btn = sender as Button;
    YourClass dc = btn.DataContext as YourClass;
    dc.IsToDelete = true;
}

I don't really like this solution, but I think, it would work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!