#wpf #validation #contentcontrol
#wpf #проверка #contentcontrol
Вопрос:
как заставить проверку работать с ContentControl? Существует класс, который отвечает за хранение значения с единицами измерения, оно отображается в элементе управления контентом через dataset, я хотел бы проверить правильность при его отображении и редактировании, например, единицы не могут иметь значение 2, или значение должно быть меньше 10000. решите это с помощью multibinding, правило проверки не выполняется при редактировании значений.
Файл Xaml:
<Window x:Class="DELETE1.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:local="clr-namespace:DELETE1"
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
mc:Ignorable="d"
x:Name="m_win"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<DataTemplate DataType="{x:Type local:ValWithUnits}">
<Border>
<DockPanel>
<ComboBox DockPanel.Dock="Right" Width="60" IsEnabled="True" SelectedIndex="{Binding Unit}" ItemsSource="{Binding Src, ElementName=m_win}" />
<TextBox Text="{Binding Val, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" IsEnabled="True"/>
</DockPanel>
</Border>
</DataTemplate>
<local:MultiBindingConverter x:Key="MultiBindingConverter" />
</Window.Resources>
<Grid>
<ContentControl x:Name="m_contentControl">
<ContentControl.Content>
<MultiBinding Mode="TwoWay" NotifyOnValidationError="True"
UpdateSourceTrigger="PropertyChanged"
diag:PresentationTraceSources.TraceLevel="High"
Converter="{StaticResource MultiBindingConverter}" >
<Binding Path="Val" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" diag:PresentationTraceSources.TraceLevel="High"></Binding>
<Binding Path="Unit" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" diag:PresentationTraceSources.TraceLevel="High"></Binding>
<MultiBinding.ValidationRules>
<local:ContentControlValidationRule ValidatesOnTargetUpdated="True" x:Name="MValidationRule"/>
</MultiBinding.ValidationRules>
</MultiBinding>
</ContentControl.Content>
</ContentControl>
</Grid>
</Window>
И файл кода:
public class ValWithUnits:INotifyPropertyChanged
{
private double m_val;
private int m_unit;
public double Val
{
get => m_val;
set
{
m_val = value;
OnPropertyChanged(nameof(Val));
}
}
public int Unit
{
get => m_unit;
set
{
m_unit = value;
OnPropertyChanged(nameof(Unit));
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ValWithUnits MyValueWithUnits { get; set; } = new ValWithUnits();
public MainWindow()
{
InitializeComponent();
var a = new Binding("MyValueWithUnits");
a.Source = this;
a.ValidatesOnDataErrors = true;
a.ValidatesOnExceptions = true;
a.NotifyOnValidationError = true;
m_contentControl.SetBinding(ContentControl.ContentProperty, a);
}
public IEnumerable<int> Src => new int[] { 1,2,3};
}
public class ContentControlValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
//Debug.Fail("validate");
return ValidationResult.ValidResu<
}
private static ValidationResult BadValidation(string msg) =>
new ValidationResult(false, msg);
}
public class MultiBindingConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return string.Format("{0}-{1}", values[0], values[1]);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return new object[] { 1, 1 };
}
}
Проверка ‘ContentControlValidationRule’, которую я устанавливаю с помощью множественной привязки, не работает.