gpt4 book ai didi

c# - 将 XAML 中的按钮可见性绑定(bind)到 View 模型?

转载 作者:行者123 更新时间:2023-11-30 12:21:06 26 4
gpt4 key购买 nike

我希望按钮在 State.AwayState.Stop 中可见,但由于某些原因,即使 State 不同于 State.AwayState.Stop

Xaml:

<Button Text="Hello" IsVisible="{Binding View}"/>

View 模型:

private bool myBool;

public bool View
{
get
{
if (State == State.Away || State == State.Gone)
{
myBool = true;
}
else
{
myBool = false;
}
return myBool;
}
}

最佳答案

您可以创建一个 IValueConverterStateVisibility

public class StateToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (value is State)
{
State state = (State)value;
switch (state)
{
case State.Away:
case State.Gone:
return Visibility.Visible;
default:
return Visibility.Collapsed;
}
}
}

public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
return State.None; // your default state
}
}

然后将按钮绑定(bind)到转换器

<Window.Resources>
<local:StateToVisibilityConverter x:Key="StateToVisibilityConverter"/>
</Window.Resources>

<Button Text="Hello" Visibility="{Binding Path=State, Converter={StaticResource StateToVisibilityConverter}}"/>

关于c# - 将 XAML 中的按钮可见性绑定(bind)到 View 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47187635/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com