为什么DataStateBehavior最初不会更新?

时间:2013-07-22 11:20:07

标签: wpf visualstatemanager

我已将ListBox绑定到我的ViewModel,包括ListBox.SelectedItem。我想根据是否选择了一个视觉状态来改变视觉状态,但以下内容最初不更新状态,因此它保持错误的状态:

<DataStateBehavior Binding="{Binding SelectedCamera}" Value="{x:Null}" TrueState="CameraSettingsUnselected" FalseState="CameraSettingsSelected"/>

为什么这样以及如何解决?

2 个答案:

答案 0 :(得分:3)

这里的问题似乎是绑定最初评估为null,因此不会触发评估和状态更改所需的更改通知。

我用以下子类修复了它:

public class FixedDataStateBehavior: DataStateBehavior
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.Loaded += (sender, routedEventArgs) =>
            {
                var bindingExpression = BindingOperations.GetBindingExpression(this, BindingProperty);
                SetCurrentValue(BindingProperty,new object());
                bindingExpression.UpdateTarget();
            };
    }
}

并像这样使用它:

<FixedDataStateBehavior Binding="{Binding SelectedCamera}" Value="{x:Null}" TrueState="CameraSettingsUnselected" FalseState="CameraSettingsSelected"/>

答案 1 :(得分:0)

上面的答案有效,但我最终创建了一个更通用的Behavior类,它只能处理所有绑定而无需单独指定它们。

public class RefreshDataContextBehavior : Behavior<FrameworkElement>
{
    protected override void OnAttached()
    {
        base.OnAttached();

        this.AssociatedObject.Loaded += AssociatedObject_Loaded;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();

        this.AssociatedObject.Loaded -= AssociatedObject_Loaded;
    }

    private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
    {
        var dc = this.AssociatedObject.DataContext;
        this.AssociatedObject.DataContext = null;
        this.AssociatedObject.DataContext = dc;
    }
}

然后简单地将它插入到具有DataContext的对象中的XAML中:

<i:Interaction.Behaviors>
    <local:RefreshDataContextBehavior />
</i:Interaction.Behaviors>