简体   繁体   中英

Setting default or a combobox with Xaml (despite Binding)

I want to Bind the selectedItem of an RadCombobox to an Observable Collection in the DataContext. This works perfectly fine. But now I want to set the default value for the combobox, this also works if I set the Variable in the Data Context. But It would be better in my opinion to set the deault within the Xaml. This should be possible with SelectedIndex="0" unfortunatly ths doesnt work anymore (no default shown) since the binding is active.

Is there an option to set deault value or the combobox while there is a binding for the SelectedItem?

<telerik:RadComboBox x:Name="radComboBox" 
                             ItemsSource="{Binding xyList, UpdateSourceTrigger=PropertyChanged}" SelectedIndex="0" SelectedItem="{Binding Selectedxy}" 
                             HorizontalAlignment="Left" Margin="0,0,0,0"  VerticalAlignment="Top" Width="250" Height="25" Grid.Row="1">
        </telerik:RadComboBox>

.

public string Selectedxy  {get;set; }

        public void FillxyDropdown()
        {
           xyList = new ObservableCollection<string>();
            foreach (KeyValuePair<string, int> Line in model.ReadxyList())
            {
                xyList.Add(Line.Key);
            }

            //Sets the default value but isnt the desired way.
            Selectedxy = "XY3.31";
        }

I agree with The One comment. You definitely should specify the default values in the View Model.

If you still want to do this in the XAML, you can set the binding mode of the SelectedItem property to OneWayToSource . In this case, Selectedxy will be updated when SelectedItem changes, but not the other way around.

<telerik:RadComboBox x:Name="radComboBox" 
          ItemsSource="{Binding xyList, UpdateSourceTrigger=PropertyChanged}" SelectedIndex="1" 
          SelectedItem="{Binding Selectedxy, Mode=OneWayToSource}" HorizontalAlignment="Left"
          Margin="0,0,0,0"  VerticalAlignment="Top" Width="250" Height="25" Grid.Row="1">
</telerik:RadComboBox>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM