我有一個TextBox
綁定到一個對象的屬性實現IDataErrorInfo
。 我設置了TextBox
的Validation.ErrorTemplate
,它工作正常。問題是我在TabControl
上有這些內容,如果將選項卡更改爲另一個,然後回到初始選項卡(其中TextBox
是),則驗證模板不會再顯示。它看起來像驗證(如值是正確的),但實際上它不是。問題與WPF驗證(IDataErrorInfo)和選項卡聚焦
這是IDataErrorInfo
對象 - 注意,是「正確」的值是2的長度的字符串:
public class Presenter : IDataErrorInfo
{
public Presenter()
{
this.Property = String.Empty;
}
public string Property { get; set; }
public string Error { get { return null; } }
public string this[string columnName]
{
get
{
if (columnName == "Property")
{
if (this.Property.Length == 2)
return null;
else
return "Invalid property length!";
}
else return null;
}
}
}
,這是XAML:
<TabControl >
<TabItem Header="tabItem1" Name="tabItem1" GotFocus="tabItem1_GotFocus">
<Grid>
<TextBox Width="100" Height="20" x:Name="txtField">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="16"/>
</Grid.ColumnDefinitions>
<AdornedElementPlaceholder Grid.Column="0"/>
<Image Source="bullets16.png" Grid.Column="1" ToolTip="{Binding CurrentItem.ErrorContent, Mode=OneWay}">
</Image>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</TextBox.Style>
<TextBox.Text>
<Binding Path="Property" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True">
</Binding>
</TextBox.Text>
</TextBox>
</Grid>
</TabItem>
<TabItem Header="tabItem2" Name="tabItem2" >
<Grid />
</TabItem>
</TabControl>
什麼任何想法我做錯了?
這也符合Expander'的'內容的問題,同樣的解決方案適用。 – 2010-03-01 22:15:08
相關的博客文章 - [WPF驗證錯誤消失在TabControl切換TabItems時](http://karlshifflett.wordpress.com/2008/02/19/wpf-validation-errors-disappear-inside-tabcontrol-when-switching- tabitems /) – akjoshi 2012-06-11 11:36:08
不是一個完整的解決方案。初始驗證僅適用於第一個選定的選項卡項目,其餘部分在您稍後切換到其中時不會自動驗證。我發現通過在代碼中手動設置DataContext在OnLoad中解決了這個問題,但它很醜陋。我仍在尋找解決方案... – MoonStom 2016-02-25 06:49:37