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

前端 未结 2 1361
刺人心
刺人心 2021-01-28 15:52

I know it is possible to do this by working with ICommand, but since this is the only place in my whole project where this is needed, I am asking myself, if there is maybe a bet

相关标签:
2条回答
  • 2021-01-28 16:33

    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>
    
    0 讨论(0)
  • 2021-01-28 16:34

    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.

    0 讨论(0)
提交回复
热议问题