如何从 ViewModel 更改视图中的 VisualState? [英] How can I change the VisualState in a View from the ViewModel?

查看:41
本文介绍了如何从 ViewModel 更改视图中的 VisualState?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 WPF 和 MVVM 的新手.我认为这是一个简单的问题.我的 ViewModel 正在执行异步调用以获取绑定到 ViewModel 中的 ObservableCollection 的 DataGrid 的数据.加载数据后,我设置了正确的 ViewModel 属性,DataGrid 可以毫无问题地显示数据.但是,我想向用户介绍正在加载数据的视觉提示.因此,使用 Blend,我将其添加到我的标记中:

I'm new to WPF and MVVM. I think this is a simple question. My ViewModel is performing an asynch call to obtain data for a DataGrid which is bound to an ObservableCollection in the ViewModel. When the data is loaded, I set the proper ViewModel property and the DataGrid displays the data with no problem. However, I want to introduce a visual cue for the user that the data is loading. So, using Blend, I added this to my markup:

        <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="LoadingStateGroup">
            <VisualState x:Name="HistoryLoading">
                <Storyboard>
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="HistoryGrid">
                        <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Hidden}"/>
                    </ObjectAnimationUsingKeyFrames>
                </Storyboard>
            </VisualState>
            <VisualState x:Name="HistoryLoaded">
                <Storyboard>
                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)" Storyboard.TargetName="WorkingStackPanel">
                        <DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Hidden}"/>
                    </ObjectAnimationUsingKeyFrames>
                </Storyboard>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>

认为我知道如何更改代码隐藏中的状态(类似于此):

I think I know how to change the state in my code-behind (something similar to this):

VisualStateManager.GoToElementState(LayoutRoot, "HistoryLoaded", true);

然而,我想要这样做的地方是在我的 ViewModel 的 I/O 完成方法中,它没有对它对应的 View 的引用.我将如何使用 MVVM 模式完成此操作?

However, the place where I want to do this is in the I/O completion method of my ViewModel which does not have a reference to it's corresponding View. How would I accomplish this using the MVVM pattern?

推荐答案

你可以这样做:

XAML

<Window x:Class="WpfSOTest.BusyWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfSOTest"
    Title="BusyWindow"
    Height="300"
    Width="300">
<Window.Resources>
    <local:VisibilityConverter x:Key="VisibilityConverter" />
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Border Grid.Row="0">
        <Grid>
            <Border>
                <Rectangle Width="400"
                           Height="400"
                           Fill="#EEE" />
            </Border>
            <Border Visibility="{Binding IsBusy, Converter={StaticResource VisibilityConverter}}">
                <Grid>
                    <Rectangle Width="400"
                               Height="400"
                               Fill="#AAA" />
                    <TextBlock Text="Busy"
                               HorizontalAlignment="Center"
                               VerticalAlignment="Center" />
                </Grid>
            </Border>
        </Grid>
    </Border>
    <Border Grid.Row="1">
        <Button Click="ChangeVisualState">Change Visual State</Button>
    </Border>
</Grid>

代码:

public partial class BusyWindow : Window
{
    ViewModel viewModel = new ViewModel();

    public BusyWindow()
    {
        InitializeComponent();

        DataContext = viewModel;
    }

    private void ChangeVisualState(object sender, RoutedEventArgs e)
    {
        viewModel.IsBusy = !viewModel.IsBusy;
    }
}

public class ViewModel : INotifyPropertyChanged
{
    protected Boolean _isBusy;
    public Boolean IsBusy
    {
        get { return _isBusy; }
        set { _isBusy = value; RaisePropertyChanged("IsBusy"); }
    }

    public ViewModel()
    {
        IsBusy = false;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler temp = PropertyChanged;
        if (temp != null)
        {
            temp(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

class VisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        switch (((Boolean)value))
        {
            case true:
                return Visibility.Visible;
        }

        return Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

-------------- 更新代码---------------

----------------------- Updated code -----------------------

XAML

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Border Grid.Row="0">
        <Grid>
            <local:MyBorder IsBusy="{Binding IsBusy}">
                <Grid>
                    <TextBlock Text="{Binding IsBusy}"
                               HorizontalAlignment="Center"
                               VerticalAlignment="Center" />
                </Grid>
            </local:MyBorder>
        </Grid>
    </Border>
    <Border Grid.Row="1">
        <Button Click="ChangeVisualState">Change Visual State</Button>
    </Border>
</Grid>

模板

<Style TargetType="{x:Type local:MyBorder}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:MyBorder}">
                <Border Name="RootBorder">
                    <Border.Background>
                        <SolidColorBrush x:Name="NormalBrush"
                                         Color="Transparent" />
                    </Border.Background>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup Name="CommonGroups">
                            <VisualState Name="Normal" />
                        </VisualStateGroup>
                        <VisualStateGroup Name="CustomGroups">
                            <VisualState Name="Busy">
                                <VisualState.Storyboard>
                                    <Storyboard>
                                        <ColorAnimation Storyboard.TargetName="NormalBrush"
                                                        Storyboard.TargetProperty="Color"
                                                        Duration="0:0:0.5"
                                                        AutoReverse="True"
                                                        RepeatBehavior="Forever"
                                                        To="#EEE" />
                                    </Storyboard>
                                </VisualState.Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <ContentPresenter />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

自定义元素

[TemplateVisualState(GroupName = "CustomGroups", Name = "Busy")]
public class MyBorder : ContentControl
{
    static MyBorder()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(MyBorder), new FrameworkPropertyMetadata(typeof(MyBorder)));
    }

    public Boolean IsBusy
    {
        get { return (Boolean)GetValue(IsBusyProperty); }
        set { SetValue(IsBusyProperty, value); }
    }

    public static readonly DependencyProperty IsBusyProperty =
        DependencyProperty.Register("IsBusy", typeof(Boolean), typeof(MyBorder), new UIPropertyMetadata(IsBusyPropertyChangedCallback));

    static void IsBusyPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        (d as MyBorder).OnIsBusyPropertyChanged(d, e);
    }

    private void OnIsBusyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (Convert.ToBoolean(e.NewValue))
        {
            VisualStateManager.GoToState(this, "Busy", true);
        }
        else
        {
            VisualStateManager.GoToState(this, "Normal", true);
        }
    }
}

这篇关于如何从 ViewModel 更改视图中的 VisualState?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆