1

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

4 Answers 4

5

take a look at FallbackValue or TargetNullvalue

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

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.
1

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

Comments

0

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}}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.