如果用户尚未指定值,我正在尝试获取ValidationRule以在有问题的组合框上显示文本。我可以让它显示,但我似乎无法使用TextTrimming =“CharacterEllipsis”使文本适合组合框的大小。如何让TextBlock适合组合框,如果用户调整窗口大小,还可以自行修正?
这是我的MainWindow.xaml:
<Window x:Class="PocAdornedElementPlaceholder.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:PocAdornedElementPlaceholder"
Title="MainWindow" Height="200" Width="150">
<Window.Resources>
<ControlTemplate x:Key="ValidationTemplate">
<Grid HorizontalAlignment="Center">
<AdornedElementPlaceholder/>
<TextBlock Foreground="Red"
TextTrimming="CharacterEllipsis"
Text="{Binding ErrorContent}"
IsHitTestVisible="False"
VerticalAlignment="Center"
Margin="5,0,0,0"/>
</Grid>
</ControlTemplate>
</Window.Resources>
<Grid>
<ComboBox Margin="10"
Validation.ErrorTemplate="{StaticResource ValidationTemplate}"
VerticalAlignment="Center"
ItemsSource="{Binding Options}">
<ComboBox.Text>
<Binding Path="SelectedValue">
<Binding.ValidationRules>
<local:MyValidationRule ValidatesOnTargetUpdated="True" />
</Binding.ValidationRules>
</Binding>
</ComboBox.Text>
</ComboBox>
</Grid>
</Window>
这是我的MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Options = new List<string>() { "Value 1", "Value 2", "Value 3", "" };
this.DataContext = this;
}
public string SelectedValue { get; set; }
public List<string> Options { get; set; }
}
这是我的MyValidationRule.cs文件:
public class MyValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (string.IsNullOrEmpty((string)value))
return new ValidationResult(false, "Value cannot be empty!");
return new ValidationResult(true, null);
}
}
任何帮助将不胜感激! 谢谢, 担
答案 0 :(得分:1)
尝试下面,TextBlock应该是装饰者的内容。我还必须更改文本块的边距以计算下拉箭头按钮。
<ControlTemplate x:Key="ValidationTemplate">
<Grid HorizontalAlignment="Center">
<AdornedElementPlaceholder>
<TextBlock Foreground="Red" TextTrimming="CharacterEllipsis" Text="{Binding ErrorContent}" IsHitTestVisible="False" VerticalAlignment="Center" Margin="5,0,20,0" />
</AdornedElementPlaceholder>
</Grid>
</ControlTemplate>