2011-08-10 49 views
3

我試圖讓一個ValidationRule在違規組合框上顯示文本,如果用戶還沒有指定一個值。我可以讓它顯示,但我似乎無法使用TextTrimming =「CharacterEllipsis」使文本適合組合框的大小。如何讓TextBlock適合組合框,並且如果用戶調整窗口大小,還可以自行更正?如何使用TextTrimming通過AdornedElementPlaceholder獲取文本塊?

這裏是我的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); 
    } 
} 

任何幫助非常感謝! 謝謝, 譚

回答

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> 
+0

非常好!非常感謝! –

相關問題