Nếu bạn muốn muốn loại kết quả khác với bool, gần đây tôi đã bắt đầu sử dụng ConverterParameter để cung cấp cho mình tùy chọn phủ nhận giá trị kết quả từ trình chuyển đổi của tôi. Dưới đây là ví dụ:
[ValueConversion(typeof(bool), typeof(System.Windows.Visibility))]
public class BooleanVisibilityConverter : IValueConverter
{
System.Windows.Visibility _visibilityWhenFalse = System.Windows.Visibility.Collapsed;
/// <summary>
/// Gets or sets the <see cref="System.Windows.Visibility"/> value to use when the value is false. Defaults to collapsed.
/// </summary>
public System.Windows.Visibility VisibilityWhenFalse
{
get { return _visibilityWhenFalse; }
set { _visibilityWhenFalse = value; }
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool negateValue;
Boolean.TryParse(parameter as string, out negateValue);
bool val = negateValue^(bool)value; //Negate the value using XOR
return val ? System.Windows.Visibility.Visible : _visibilityWhenFalse;
}
...
Bộ chuyển đổi này chuyển đổi bool thành System.Windows.Visibility. Tham số cho phép nó phủ nhận bool trước khi chuyển đổi trong trường hợp bạn muốn hành vi nghịch đảo. Bạn có thể sử dụng nó trong một yếu tố như thế này:
Visibility="{Binding Path=MyBooleanProperty, Converter={StaticResource boolVisibilityConverter}, ConverterParameter=true}"
Thật không may nếu bạn đã sử dụng công cụ chuyển đổi giá trị trong ràng buộc thì bạn phải sử dụng một số kỹ thuật đường ống/chuỗi để loại bỏ giá trị được trả về bởi giá trị đó chuyển đổi. – jpierson