您正在綁定到文本的長度,但您需要一個從長度到布爾的轉換器,因爲IsEnabled屬性需要布爾值。
public class NumToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value!=null && value is int)
{
var val = (int)value;
return (val==0) ? false : true;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value!=null && value is bool)
{
var val = (bool)value; return val ? 1 : 0;
}
return null;
}
}
爲此和資源添加一個本地xmlns。
xmlns:local="clr-namespace:YourNamespace"
這是對轉換器類的引用。
<local:NumToBoolConverter x:Key="NumToBoolConverter"/>
在您的Binding部分補充一點:
Converter={StaticResource NumToBoolConverter}
這可能是你最後的菜單項定義:
<MenuItem x:Name="DeleteContact"
Header="Delete Contact"
IsEnabled="{Binding ElementName=ContactDetails.ContactNameTextBox,
Path=Text.Length,
Converter={StaticResource NumToBoolConverter},
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"/>