您可以使用旨在将您的状态 (int) 转换为控件是否启用 (bool) 的转换器。
[ValueConversion(typeof(int), typeof(bool))]
public class StatusToEnabledConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int status = (int)value;
switch (status)
{
case 1: return true;
case 2: return false;
default: return false;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
然后,您可以将要影响的所有控件的 isEnabled 绑定到您的状态代码,并使用该转换器进行转换。
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:StatusToEnabledConverter x:Key="statusConvert"/>
</Window.Resources>
<Grid>
<Button IsEnabled="{Binding status, Converter={StaticResource statusConvert}}" />
</Grid>
</Window>
对于可见性,您可以执行完全相同的操作,使用 StatusToVisibilityConverter 并返回 Visibility.Visible 或 Visibility.Collapsed。
...或者,如果您想获得技术并重用以前的转换器,您可以设计一个 boolToVisibilityConverter 并将上面的转换器链接到这个新的转换器。