在WPF MVVM验证时将焦点设置为UI控件。HasError

问题描述 投票:0回答:2

问题:Validation.HasError通过INotifyDataErrorInfo实现自动突出显示具有错误的控件。

我的问题是,当它具有ERror时,我需要集中精力于该特定控件。

我该怎么做?

mvvm data-binding wpf-controls wpf-4.5
2个回答
0
投票

我已经阅读了Stackoverflow和其他站点上的几篇文章,最后我希望解决这个问题。

   <Style TargetType="TextBox" >
                        <Setter Property="OverridesDefaultStyle" Value="false"/>
                        <Setter Property="VerticalAlignment" Value="Center"/>
                        <Setter Property="HorizontalAlignment" Value="Left"/>
                        <Setter Property="Margin" Value="5,3" />
                        <Style.Triggers>
                            <Trigger Property="Validation.HasError" Value="True">
                                <Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}"/>
                            </Trigger>
                        </Style.Triggers>
                    </Style>

设置FocusedElement可以解决问题。 :)也可以使用DataTrigger通过ViewModel中的布尔属性(而不是简单的触发器)来设置焦点。


0
投票

Wpf MVVM使用的FocusExtension行为

 public static class FocusExtension
{
    public static bool GetIsFocused(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsFocusedProperty);
    }
    public static void SetIsFocused(DependencyObject obj, bool value)
    {
        obj.SetValue(IsFocusedProperty, value);
    }
    public static readonly DependencyProperty IsFocusedProperty =
           DependencyProperty.RegisterAttached(
                 "IsFocused", typeof(bool), typeof(FocusExtension),
                 new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));
    private static void OnIsFocusedPropertyChanged(DependencyObject d,
           DependencyPropertyChangedEventArgs e)
    {   
        var uie = (UIElement)d;

        if ((bool)e.NewValue)
        {
            uie.Focus();

        }


    }
}

Xaml代码

            <TextBox
                    behavior:FocusExtension.IsFocused="{Binding NameFocus}"
                    Text="{Binding Customer_Name,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged }"
                    x:Name="txtname" 
                    CharacterCasing="Upper"
                    Grid.Column="3"
                    Grid.Row="1"
                    TextWrapping="Wrap" 
                    BorderThickness="1,1,1,0.5"
                    >

            </TextBox>

视图模型中的MVVM属性

 public const string NameFocusPropertyName = "NameFocus";
    private bool _NameFocus = default(bool);
    public bool NameFocus
    {
        get
        {
            return _NameFocus;
        }

        set
        {
            if (_NameFocus == value)
            {
                return;
            }

            _NameFocus = value;
            RaisePropertyChanged(NameFocusPropertyName);
        }
    }

设置加载事件

NameFocus=true
© www.soinside.com 2019 - 2024. All rights reserved.