体系结构:如何实现影响多个 UI 对象的状态

本文关键字:UI 对象 状态 影响 何实现 实现 体系结构 | 更新日期: 2023-09-27 18:32:18

我只能提出以下我认为很不满意的问题的解决方案:

我希望几个 UI 元素根据我希望能够从应用程序中的多个位置修改的状态(0-8 之间的整数)更改它们的行为(大多数只是取消/启用或更改可见性)。

有没有比在我的状态属性的设置器中实现一个巨大的开关/案例块更优雅的方法(实现策略模式似乎并不是更好的解决方案,因为我只是切换"一些"标志)?也许你可以在这里用数据绑定做一些魔术?目前,我在我的视图模型中为我需要更改的所有 UI 对象属性使用专用标志(这些属性又在状态属性的设置器中被修改......

我想某种条件数据绑定将是我能想到的最优雅的事情,但如果有其他可行的方法来实现这一点,我想得到一些输入。

体系结构:如何实现影响多个 UI 对象的状态

您可以使用旨在将状态 (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 并将上面的转换器链接到这个新转换器。