1

ユーザーコントロールを表示するために、ツールチップを使用したスト​​ック/標準の赤い境界線の検証が必要です。以下のコードを参照してください。メインページとUserControlがあります。

UserControlにはテキストボックスとボタンがあります。UserControlsはIdプロパティにバインドし、このIdをTextBox内に表示します。

メインページにはUserControlとTextBoxがあります。それらはFirstValueとSecondValueにバインドされました。どちらのプロパティもエラーを発生させます。テキストボックスに何かを入力/変更すると、境界線と概要が表示されます。UserControlでテキストを変更すると(要約にはエラーが表示されますが、境界線は表示されません)、エラーをクリックすると、ボタンにフォーカスが表示され、TextBoxに移動しません。どうすれば修正できますか?UserControl全体を赤い境界線の内側に配置したいと思います。

MainPage XAML:

<UserControl x:Class="SilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="275" d:DesignWidth="402" xmlns:my="clr-namespace:SilverlightApplication1" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

    <Grid x:Name="LayoutRoot" Background="White" Width="300" HorizontalAlignment="Left">
        <Grid.RowDefinitions>
            <RowDefinition Height="30" />
            <RowDefinition Height="40" />
            <RowDefinition Height="30" />
            <RowDefinition Height="30" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <TextBox Grid.Row="2" Margin="3" Text="{Binding SecondValue, Mode=TwoWay, NotifyOnValidationError=True}"/>
        <my:TestUserControl Margin="3" Id="{Binding FirstValue, Mode=TwoWay, NotifyOnValidationError=True}"/>
        <sdk:ValidationSummary Grid.Row="4" Name="validationSummary1" />
    </Grid>
</UserControl>

MainPage CS

using System.Windows.Controls;


namespace SilverlightApplication1
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;

    public partial class MainPage : UserControl, INotifyDataErrorInfo, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
        readonly Dictionary<string, List<string>> _currentErrors;

        private string _firstValue;
        private string _secondValue;

        public MainPage()
        {
            InitializeComponent();
            _currentErrors = new Dictionary<string, List<string>>();
            _firstValue = "test1";
            _secondValue = "test2";
            LayoutRoot.DataContext = this;
        }


        public string FirstValue
        {
            get { return _firstValue; }

            set
            {
                _firstValue = value;
                CheckIfValueIsValid("FirstValue", value);
                this.OnPropertyChanged("FirstValue");
            }
        }

        public string SecondValue
        {
            get { return _secondValue; }
            set
            {
                _secondValue = value;
                CheckIfValueIsValid("SecondValue", value);
                this.OnPropertyChanged("SecondValue");
            }
        }

        public void CheckIfValueIsValid(string propertyName, string value)
        {
            ClearErrorFromProperty(propertyName);

            AddErrorForProperty(propertyName, "Bad value");
        }

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public IEnumerable GetErrors(string propertyName)
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                return (_currentErrors.Values);
            }
            MakeOrCreatePropertyErrorList(propertyName);

            return _currentErrors[propertyName];
        }

        public bool HasErrors
        {
            get
            {
                return (_currentErrors.Where(c => c.Value.Count > 0).Count() > 0);
            }
        }

        void FireErrorsChanged(string property)
        {
            if (ErrorsChanged != null)
            {
                ErrorsChanged(this, new DataErrorsChangedEventArgs(property));
            }
        }

        public void ClearErrorFromProperty(string property)
        {
            MakeOrCreatePropertyErrorList(property);

            _currentErrors[property].Clear();
            FireErrorsChanged(property);
        }

        public void AddErrorForProperty(string property, string error)
        {
            MakeOrCreatePropertyErrorList(property);
            _currentErrors[property].Add(error);
            FireErrorsChanged(property);
        }

        void MakeOrCreatePropertyErrorList(string propertyName)
        {
            if (!_currentErrors.ContainsKey(propertyName))
            {
                _currentErrors[propertyName] = new List<string>();
            }
        }


    }
}

UserControl XAML:

<UserControl x:Class="SilverlightApplication1.TestUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="30" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <Button Content="..." Grid.Column="1" Padding="10,0" />
        <TextBox Text="{Binding Id, Mode=TwoWay}" />
    </Grid>
</UserControl>

UserControl CS:

using System.Windows.Controls;

namespace SilverlightApplication1
{
    using System.ComponentModel;
    using System.Windows;

    public partial class TestUserControl : UserControl, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public TestUserControl()
        {
            InitializeComponent();
            LayoutRoot.DataContext = this;
        }


        public string Id
        {
            get { return (string)base.GetValue(IdProperty); }
            set
            {
                base.SetValue(IdProperty, value);
                this.OnPropertyChanged("Id");
            }
        }

        public static DependencyProperty IdProperty =
            DependencyProperty.Register(
            "Id",
            typeof(string),
            typeof(TestUserControl),
            new PropertyMetadata(OnIdChanged));

        private static void OnIdChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (DesignerProperties.IsInDesignTool) return;

            var lookup = d as TestUserControl;
            lookup.OnPropertyChanged("Id");
        }

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

    }
}
4

2 に答える 2

3

サンプルを機能させるには、ファイルからすべてのコードを削除し、TestUserControl.xaml.csバインディングを修正する必要があります。このような:

<Button Content="..." Grid.Column="1" Padding="10,0" />
<TextBox Text="{Binding FirstValue, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnNotifyDataErrors=True}" />

そして背後にある空のコード:

public partial class TestUserControl : UserControl
{
    public TestUserControl()
    {
        InitializeComponent();
    }
}

次に、あなたの別の質問

3つのボックスすべて(1つの長方形)の周りに赤い境界線を表示します

これは、プロパティにバインドすることで実現できHasErrorます。あなたのコードによると、それはそう見えるでしょう:

<Grid x:Name="LayoutRoot" Background="White">
   <!-- ... -->
   <Border BorderBrush="Red" BorderThickness="1" 
            Grid.ColumnSpan="2" IsHitTestVisible="False"
            Visibility="{Binding HasErrors, Converter={StaticResource BooleanToVisibilityConverter}}" />

プロパティがtrueに設定されているBorderときに表示される赤い要素を追加しました。ただし、コードのどこかでHasError呼び出す必要があります。OnPropertyChanged("HasError")

別の方法:UserControlの代わりにカスタムコントロールを作成する。検証に関するこの質問への回答として、カスタムコントロールに検証を実装する方法についての過度の説明を投稿しました。  

より具体的な答えを出すことはできますが、現在のコードに基づいて何かを実装することは困難になっているため、ビューモデルをビューから分離して投稿のコードを修正する必要があります。INotifyDataErrorInfo:WPFおよびSilverlightValidationを使用した検証の実装に関する私の投稿を確認してください。

または、検証クラスを直接ダウンロードすることもできます。

その後、コードははるかに単純になり、より複雑な質問についてお手伝いできるようになります。

于 2011-10-30T17:34:22.313 に答える
0

変化する

<TextBox Text="{Binding Id, Mode=TwoWay}" />

<TextBox Text="{Binding Id, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnDataErrors=True}" />
于 2011-10-30T09:51:17.423 に答える