1
votes

in my WPF application I refer to a selected value of a combobox with

{Binding Source={x:Reference myComboBox} ,Path=SelectedItem}

I do this inside of DataGrid Columns.

This is throwing a null reference exception at design time (not run time). Is there any way to fix this, or can I access the selected Item somehow other than that?

ComboBox:

<ComboBox         x:Name="myComboBox"
                  ItemsSource="{Binding MyItems}"
                  DisplayMemberPath="Name"
                  SelectedItem="{Binding SelectedItem}"
                   />

DataGridTextColumn:

<DataGridTextColumn HeaderStyle="{DynamicResource myStyle}"  Visibility="{Binding Source={x:Reference myComboBox} ,Path=SelectedItem, Converter={StaticResource ConvertSomething}, ConverterParameter={StaticResource Something}}" Header="MyHeader " Width="*" Binding="{Binding Path=MyBindingName}" />
2
Can you post the full code..?NullReferenceException
@NullReferenceException I hope this is enough.Florian
What a version of VisaulStudio are you using?Anatoliy Nikolaev
2013 Premium with Update 1Florian

2 Answers

3
votes

In this case try using proxy of Freezable type, that inherit DataContext. Now we do not need to refer to ComboBox because we will have a property that is in DataContext. I think, this is a more universal solution:

BindingProxy

public class BindingProxy : Freezable
{
    #region Overrides of Freezable

    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }

    #endregion

    public object Data
    {
        get 
        {
            return (object)GetValue(DataProperty); 
        }

        set
        {
            SetValue(DataProperty, value);
        }
    }

    public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data",
                                                                                typeof(object),
                                                                                typeof(BindingProxy));
}

XAML

<DataGrid>
    <DataGrid.Resources>
        <local:BindingProxy x:Key="bindingProxy" Data="{Binding}" />
    </DataGrid.Resources>

    <DataGrid.Columns>
        <DataGridTextColumn Visibility="{Binding Path=MySelectedItem, 
                                                 Converter={StaticResource ConvertSomething}, 
                                                 ConverterParameter={StaticResource Something}}" 
                                                 Source={StaticResource bindingProxy}}" />
    </DataGrid.Columns>
</DataGrid>
1
votes

why not try {Binding ElementName=myComboBox ,Path=SelectedItem}