views:

86

answers:

4

Hello, I have a TreeView and a couple of other controls like TextBoxs and ComboBoxs. The textboxes are bound to the selected item in the treeview like 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 kinda 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 tree view 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

A: 

take a look at FallbackValue or TargetNullvalue

qntmfred
A: 

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.

Robert Rossney
Sure that works for displaying text, but it won't support updating the Name property, and it also doesn't work if you have a lot of properties on your object.
HaxElit
A: 

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}}"
HaxElit
A: 

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

Ian Ringrose