2016-10-12 2 views
0

У меня есть элемент ItemsControl для отображения текстовых полей. Я хочу настроить проверку, поэтому, если все переводы пустые, произошла ошибка, а поля отмечены как «ошибка». Есть ли возможность сделать это?Проверка элементов управления в wpf не работает

Мой XAML: класс

<ItemsControl x:Name="LanguageItemsControl" ItemsSource="{Binding Path=Translations, Mode=TwoWay}" 
      LostFocus="OnLostFocus" > 
<ItemsControl.ItemTemplate> 
    <DataTemplate> 
     <Grid Margin="5,2,5,2"> 
      <Grid.ColumnDefinitions> 
       <ColumnDefinition Width="47*"/> 
       <ColumnDefinition Width="53*"/> 
      </Grid.ColumnDefinitions> 
      <TextBlock Grid.Column="0" x:Name="ItemLabel" VerticalAlignment="Center" 
      Text="{Binding Path=Key, StringFormat={x:Static res:Resources.lblCaption}}" /> 
      <TextBox Grid.Column="1" x:Name="ItemText" VerticalAlignment="Center" 
       HorizontalAlignment="Stretch" Margin="2,0,22,0" 
      Text="{Binding Path=Value, Mode=TwoWay, 
      UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=true, NotifyOnValidationError=true}" 
       LostFocus="OnLostFocus" 
       AcceptsReturn="True" 
       MaxLines="2" 
       ScrollViewer.VerticalScrollBarVisibility="Auto" 
        MaxLength="150"> 
      </TextBox> 
     </Grid> 
    </DataTemplate> 
</ItemsControl.ItemTemplate> 
</ItemsControl> 

моей модели реализует от IDataErrorInfo и INotifyPropertyChanged Переводы является ObservableCollection пользовательского типа «LanguageValue» с открытыми свойствами, ключ и значение.

У меня была модель string this[string columnName], которая отлично работает с простыми текстовыми полями (за пределами ItemsControl), но как это сделать с моими товарами? У меня есть что-то вроде:

public string this[string columnName] 
{ 
get 
{ 
    string result = null; 
    ... 
    if (columnName == "Translations" || columnName == "ItemText") 
    { 
     if (Translations.All(t => string.IsNullOrEmpty(t.Value))) 
      result = Properties.Resources.errMsgEnterName; 
    } 
... 

Но, конечно, это не сработало.

Любые предложения?

ответ

2

Конечно, я даю вам полную реализацию, но только с свойством «Значение». Сделайте то же самое со всеми другими свойствами, которые вы хотите проверить:

1.Translation Модель с реализацией интерфейса IDataErrorInfo:

public class Translation : BindableBase, IDataErrorInfo 
{ 
    public string Value { get; set; } 

    public string this[string propertyName] 
    { 
     get 
     { 
      return GetErrorForPropery(propertyName); 
     } 
    } 

    public string Error { get; } 

    private string GetErrorForPropery(string propertyName) 
    { 
     switch (propertyName) 
     { 
      case "Value": 

       if (string.IsNullOrEmpty(Value)) 
       { 
        return "Please enter value"; 
       } 

       return string.Empty; 

      default: 
       return string.Empty; 
     } 
    } 
} 

2.Initialize Перевод в вашем ViewModel:

public ObservableCollection<Translation> Translations { get; set; } 

    public MainViewModel() 
    { 
     Translations = new ObservableCollection<Translation> 
     { 
      new Translation {Value = "A"}, 
      new Translation(), 
      new Translation {Value = "C"} 
     }; 
    } 

3. Xaml с ValidatesOnDataErrors по значению TextBox:

<ItemsControl x:Name="LanguageItemsControl" ItemsSource="{Binding Path=Translations, Mode=TwoWay}"> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <Grid Margin="5,2,5,2"> 
        <Grid.ColumnDefinitions> 
         <ColumnDefinition Width="47*"/> 
         <ColumnDefinition Width="53*"/> 
        </Grid.ColumnDefinitions> 
        <TextBox Grid.Column="0" x:Name="ItemLabel" VerticalAlignment="Center" Text="{Binding Path=Value, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" /> 
       </Grid> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl> 

4.That покажет красную рамку вокруг пустой TextBox, если вы хотите, чтобы отобразить messeage ошибки при наведении overthe TextBox вам нужна подсказка,:

<Window x:Class="WpfApplication1.MainWindow" 
    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" 
    xmlns:customControlLib="clr-namespace:CustomControlLib;assembly=CustomControlLib" 
    xmlns:sys="clr-namespace:System;assembly=mscorlib" 
    mc:Ignorable="d" 
    Title="MainWindow" 
    DataContext="{StaticResource MainViewModel}"> 
<Window.Resources> 
    <Style x:Key="TextBoxStyle" TargetType="{x:Type TextBox}"> 
     <Style.Triggers> 
      <Trigger Property="Validation.HasError" Value="true"> 
       <Setter Property="ToolTip" 
          Value="{Binding RelativeSource={RelativeSource Self}, 
          Path=(Validation.Errors)[0].ErrorContent}"/> 
      </Trigger> 
     </Style.Triggers> 
    </Style> 
</Window.Resources> 
<Grid> 
    <ItemsControl x:Name="LanguageItemsControl" ItemsSource="{Binding Path=Translations, Mode=TwoWay}"> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <Grid Margin="5,2,5,2"> 
        <Grid.ColumnDefinitions> 
         <ColumnDefinition Width="47*"/> 
         <ColumnDefinition Width="53*"/> 
        </Grid.ColumnDefinitions> 
        <TextBox Grid.Column="0" x:Name="ItemLabel" Style="{StaticResource TextBoxStyle}" VerticalAlignment="Center" Text="{Binding Path=Value, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" /> 
       </Grid> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
    </ItemsControl>  

+0

Хорошее решение! Но мне не нужно показывать ошибку, когда только одно значение пусто. Я хочу ошибку, когда все они пусты. – Ksice

Смежные вопросы