有人可以幫助我,我如何從我的自定義用戶控件訪問HasError屬性?訪問UserControl的Validation.HasError
<UserControl.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Margin" Value="0,2,0,2" />
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel LastChildFill="true">
<Border Background="Red" DockPanel.Dock="right" Margin="5,0,0,0" Width="20" Height="20" CornerRadius="10"
ToolTip="{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
<!--<TextBlock Text="!" VerticalAlignment="center" HorizontalAlignment="center" FontWeight="Bold" Foreground="white">
</TextBlock>-->
</Border>
<AdornedElementPlaceholder Name="customAdorner" VerticalAlignment="Center" >
<Border BorderBrush="red" BorderThickness="1" />
</AdornedElementPlaceholder>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<Grid x:Name="Layout" DataContext="{Binding RelativeSource={RelativeSource AncestorType=UserControl}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Name="TbHostname" Grid.Column="1"
VerticalContentAlignment="Center" MinWidth="200">
<TextBox.Text>
<Binding Path="Hostname" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True" NotifyOnValidationError="True">
<Binding.ValidationRules>
<serverStarter2:HostnameValidator ErrorMessage="Wrong hostname format."/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</Grid>
這是我的自定義用戶控件,即在MainWindow.xaml使用。我想要什麼,當一切正常時,啓用提交按鈕,否則,禁用它。
這裏是內部MainWindow.xaml的按鈕代碼:
<Button Content="Test connection" Command="{Binding ConnectionViewModel.TestConnectionCommand}"
>
<Button.Style>
<Style TargetType="{x:Type Button}" >
<Style.Triggers>
<DataTrigger Binding="{Binding Path=(Validation.HasError), ElementName=StudioHostname}" Value="True">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
的ElementName = StudioHostname是我的用戶名稱。
謝謝你的回答,我會試試 – JurajPupak
我有點困惑。對於我的用戶控件,我沒有任何虛擬機。主機名是依賴屬性。你的意思是我應該從INofityDataErrorInfo繼承UserControl並實現接口? – JurajPupak
在這種情況下,是的。 UserControl應該實現該接口。然後您可以綁定到UserControl的HasErrors屬性。 – mm8