0

I have a multi columns combobox. After combo population, I try to set the default values, but I get this error message

Object reference not set to an instance of an object.

This my code

Property

public ObservableCollection<Model_Sedi> Sedi { get; set; }
private Model_Sedi _Sedi_Search;
public Model_Sedi Sedi_Search {
get { return _Sedi_Search; }
set {
    _Sedi_Search = value;
    OnPropertyChanged("Sedi_Search");
    }
    }

this is XAML

  <ComboBox x:Name="Cmb_Sede"                    
        ItemsSource="{Binding Sedi, Mode=TwoWay}"
                      SelectedValuePath="Value"
                      SelectedItem="{Binding Sedi_Search, Mode=TwoWay}" 

                      VerticalAlignment="Top" Width="189">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding IdSede, UpdateSourceTrigger=PropertyChanged}"></TextBlock>
                    <TextBlock Text="{Binding Sede, UpdateSourceTrigger=PropertyChanged}" Padding="10,0,0,0"></TextBlock>
                </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
        <ComboBox.Effect>
            <DropShadowEffect Color="#FF0A0A0A" Opacity="0.6"/>
        </ComboBox.Effect>
    </ComboBox>

Now, how can I set the default values ? (like this doesn't work)

Sedi_Search.Sede = "ABC"
Sedi_Search.IdSede = 111
Jehof
  • 34,674
  • 10
  • 123
  • 155
Alan392
  • 675
  • 2
  • 12
  • 26

2 Answers2

1

You need to set the Sedi_Search property to a matching object from the Sedi collection. Just use LINQ for this:

Sedi_Search = Sedi.SingleOrDefault(x => x.Sede == "ABC" && x.InSede == 111);

Another way of writing this:

Func<Model_Sedi, bool> isMatch = delegate(Model_Sedi x)
{
    return x.Sede == "ABC" && x.InSede == 111;
};

Sedi_Search = Sedi.SingleOrDefault(isMatch);

The first version is just a shorthand version of the second. x is just a variable name used by the delegate/lambda expression. This SO question might prove useful: Linq and lambda expression.

Community
  • 1
  • 1
Steven Rands
  • 5,160
  • 3
  • 27
  • 56
0

Change SelectedValuePath="IdSede" in XAML and in View Model you have to do what Steven Rands is saying.

Community
  • 1
  • 1
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208