开发者

WPF Conditional Binding

开发者 https://www.devze.com 2022-12-16 15:23 出处:网络
I have a TreeView and a couple of other controls like TextBoxes and ComboBoxes. The TextBoxes are bound to the selected item in the TreeViewlike this:

I have a TreeView and a couple of other controls like TextBoxes and ComboBoxes. The TextBoxes are bound to the selected item in the TreeViewlike this:

Text="{Binding SelectedItem.Name, ElementName=groupTreeView}"

This works fine if all the elements in my TreeView have a Name Property.

I was wondering if there was a way to do some kind of conditional bind that would say:

if SelectedItem is MyTreeType
    then bind
else
    disable the element

Is it possible to do something like this? Right now I'm just getting binding errors thrown and that seems a little dirty. My TreeView is databound and has a couple different type of classes in it so that's why I'm looking for some kind of conditional开发者_如何转开发 binding.

Thanks, Raul


take a look at FallbackValue or TargetNullvalue


This is why it's always a good idea to override ToString in your view classes. Do this, and you can just bind Text to SelectedItem.


Look at using the Model-View ViewModel (MVVM) design pattern, then your binding code is simple and the logic is in a testable class. It is more work to start with but tends to lead to fewer problems in the long term.

Here is a very good video you should take a look at: Jason Dolinger on Model-View-ViewModel


Well I ended up creating a "CastingConverter" that I send the type in as a parameter

public class CastingConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return null;

        if (parameter == null)
            throw new ArgumentNullException("parameter");

        var type = parameter as Type;

        if (type == null)
            throw new ArgumentException("parameter must be a type");

        var itemType = value.GetType();

        if (type.IsAssignableFrom(itemType))
            return value;

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

Then I just bound with the following

DataContext="{Binding SelectedItem, ElementName=groupTreeView, Converter={StaticResource CastingConverter}, ConverterParameter={x:Type vm:GroupViewModel}}"
0

精彩评论

暂无评论...
验证码 换一张
取 消