如何从ViewModel更改View中的VisualState?

时间:2010-06-15 16:33:09

标签: wpf silverlight mvvm

我是WPF和MVVM的新手。我认为这是一个简单的问题。我的ViewModel正在执行异步调用以获取DataGrid的数据,该DataGrid绑定到ViewModel中的ObservableCollection。加载数据时,我设置了正确的ViewModel属性,DataGrid显示数据没有问题。但是,我想为用户引入数据加载的视觉提示。所以,使用Blend,我将其添加到我的标记中:

        <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>

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

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

但是,我想要这样做的地方是我的ViewModel的I / O完成方法,它没有引用它的相应View。我如何使用MVVM模式实现这一目标?

3 个答案:

答案 0 :(得分:12)

执行此操作的标准方法通常是在viewmodel中具有属性(依赖属性或参与INotifyPropertyChanged的属性),这表示数据正在加载 - 可能是bool IsLoadingData或类似。您在开始加载时将其设置为true,并在完成后将其设置为false。

然后,您将在视图中将触发器或可视状态绑定到此属性,并使用该视图来描述如何向用户显示数据正在加载。

此方法维护视图模型是用户视图的逻辑表示的分离,并且不需要参与实际显示 - 或者具有动画,视觉状态等知识。

使用DataStateBehavior根据Silverlight中的绑定更改视觉状态:

<TheThingYouWantToModify ...>
 <i:Interaction.Behaviors>
   <ei:DataStateBehavior Binding="{Binding IsLoadingData}" Value="true" TrueState="HistoryLoading" FalseState="HistoryLoaded" />
 </i:Interaction.Behaviors>
</TheThingYouWantToModify >

答案 1 :(得分:7)

您可以这样做:

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();
    }
}

-----------------------更新后的代码---------------------- -

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);
        }
    }
}

答案 2 :(得分:2)

我过去所做的是在我的VM中声明View订阅的事件。然后,当我想指示忙指示符应该消失时,我在VM中引发事件。