WPF:如何从Button的DataTemplate设置bool为true? [英] WPF: How to set bool to true from DataTemplate for Button?
问题描述
我知道可以通过与ICommand一起使用来做到这一点,但是由于这是我整个项目中唯一需要这样做的地方,所以我问自己,是否有比实现RelayCommand和ICommand和
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 better solution than implementing RelayCommand and ICommand and an additional method in my otherwise property-only class?
也许我的情况可能对这里有帮助:
我有一个ListView绑定到一个属性列表(这是我制作来展示这些的自定义类)。
在每行条目中都有一个按钮,我想将 IsToDelete -Property设置为true。
Maybe my scenario may help here: I have a ListView which is bound to a list of properties (this is a custom-class I made to display those). I have a button in eacht row of entries, that I want to set the "IsToDelete"-Property to true.
如果 IsToDelete为true,我在ListView中显示的所有控件都将折叠。
If "IsToDelete" is true, all the controls I show in my ListView will collapse.
在DataTemplates中,整个逻辑到此为止,我按钮的外观如下:
The whole logic is up to this point in DataTemplates, the one for my button looks like this:
<DataTemplate x:Key="DeleteButtonTemplate">
<Button Name="bt_Delete"
Command="{Binding RelativeSource={RelativeSource AncestorType=ListView}, Path=ItemSource.DeleteClicked}">
<Image Height="16" Width="16" Source="Images\RecycleBin\VSO_RecycleBin_16x.png"/>
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<DataTrigger Binding="{Binding IsToDelete}" Value="True">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</DataTemplate>
请注意,此DataTemplate中的命令当前未按预期运行,这就是为什么我什至问题;)
Note the command in this DataTemplate is currently not working as intended, that is why I even got to the question ;)
在最佳情况下,我只需要做以下事情:
In the optimal case I'd just have to do something like:
<Setter Property="{Binding IsToDelete}" Value="True"/>
因此,有没有办法像这样解决问题,或者至少比ICommand复杂
So, is there a way to solve it like this or at least in a less complicated way than ICommand with RelayCommand?
推荐答案
为什么不使用 ToggleButton
并绑定<$ c将$ c> IsChecked 属性更改为viewModel的 IsToDelete
属性?
why not use ToggleButton
and bind IsChecked
property to IsToDelete
property of a viewModel?
简化示例 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>
这篇关于WPF:如何从Button的DataTemplate设置bool为true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!