我有按钮:
<Button Content="Stop loading" />
在 ViewModel 中,我有属性 IsLoaded。我不想编写属性 IsNotLoaded 但我想在绑定(bind)中使用 IsLoaded 并在 IsLoaded = true 时禁用按钮。
如何实现这样的东西:
<Button Content="Stop loading" IsEnabled="{Binding !IsLoaded}" />
附言如果它比编写附加属性更困难,我将使用 IsNotLoaded 属性。
这样做的标准方法是制作一个 IValueConverter
这将反转你的 bool 值。虽然创建此类比添加新属性更困难,但它是完全可重用的 - 因此稍后,您可以在其他绑定(bind)中重用它(不会用大量 !Property 属性污染您的 ViewModel)。
这个类看起来像这样:
[ValueConversion(typeof(bool), typeof(bool))]
public class InvertBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool booleanValue = (bool)value;
return !booleanValue;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
bool booleanValue = (bool)value;
return !booleanValue;
}
}
然后,您可以将其添加到您的资源中:
<src:InvertBoolConverter x:Key="invertBoolConverter"/>
一旦你有了这个,你会像这样使用它:
<Button Content="Stop loading"
IsEnabled="{Binding IsLoaded, Converter={StaticResource invertBoolConverter}}"
/>