在此question中,我已经遵循了两个示例,但是我无法将视图模型中的布尔值绑定到视图中的按钮。我正在使用另一个按钮来切换另一个按钮是否应该可见,任何人都可以看到问题所在吗?
当前,我正在尝试将布尔值绑定到按钮的可见性,即使我已经测试过布尔值在True / False之间切换,这也无法正常工作。我使用的另一种方法是使用数据触发器来更改可见性。我已注释掉此方法,因为它不起作用。
查看
<Button Canvas.Left="300" Canvas.Top="235" Click="ShowEquipmentItems" Cursor="Hand" Visibility="{Binding ShowButtons, Converter={StaticResource BooleanToVisibilityConverter}}">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Content">
<Setter.Value>
<StackPanel>
<Image Source="../Images/Green spot icon.png" Height="35" Width="35" />
</StackPanel>
</Setter.Value>
</Setter>
<Setter Property="Visibility" Value="Collapsed"/>
<!--<Style.Triggers>
<DataTrigger Binding="{Binding ShowButtons}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>-->
</Style>
</Button.Style>
</Button>
<Button Canvas.Right="10" Canvas.Top="388" Command="{Binding ToggleButtonCommand}" Cursor="Hand" Height="50" Width="50" />
查看模型
public class CabinViewViewModel : BindableBase, ICabinViewViewModel
{
public bool ShowButtons { get; set; }
public DelegateCommand ToggleButtonCommand { get; private set; }
public CabinViewViewModel()
{
ToggleButtonCommand = new DelegateCommand(ToggleButtons, CanToggleButtons);
ShowButtons = true;
}
public void ToggleButtons()
{
ShowButtons = !ShowButtons;
System.Console.WriteLine("Toggle Buttons" + ShowButtons.ToString());
}
public bool CanToggleButtons()
{
return true;
}
}
答案 0 :(得分:2)
很明显,@ mm8的答案同样有效,但恕我直言,更干净的方法是像这样使用BooleanToVisibilityConverter:
<Button Visibility="{Binding ShowButtons, Converter={StaticResource BooleanToVisibilityConverter}}">
也可以为您节省很多代码,而且更易于阅读。
答案 1 :(得分:0)
不要设置本地Visibility
属性:
<Button Canvas.Left="300" Canvas.Top="235" Click="ShowEquipmentItems" Cursor="Hand">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Content">
<Setter.Value>
<StackPanel>
<Image Source="../Images/Green spot icon.png" Height="35" Width="35" />
</StackPanel>
</Setter.Value>
</Setter>
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ShowButtons}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
如文档中所述,本地值优先于样式设置器:https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/dependency-property-value-precedence
您还应该在视图模型中为PropertyChanged
属性引发ShowButtons
事件:
public class CabinViewViewModel : BindableBase, ICabinViewViewModel
{
private bool _showButtons;
public bool ShowButtons
{
get { return _showButtons; }
set { SetProperty(ref _showButtons, value); }
}
...
}