简体   繁体   English

使用 Xaml 设置默认值或 combobox(尽管有绑定)

[英]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.我想将 RadCombobox 的 selectedItem 绑定到 DataContext 中的 Observable 集合。 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.但是现在我想为 combobox 设置默认值,如果我在数据上下文中设置变量,这也可以。 But It would be better in my opinion to set the deault within the Xaml.但在我看来,最好在 Xaml 中设置默认值。 This should be possible with SelectedIndex="0" unfortunatly ths doesnt work anymore (no default shown) since the binding is active.这应该是可能的SelectedIndex="0"不幸的是,由于绑定处于活动状态,因此不再起作用(未显示默认值)。

Is there an option to set deault value or the combobox while there is a binding for the SelectedItem?当 SelectedItem 有绑定时,是否有设置默认值或 combobox 的选项?

<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.我同意The One 的评论。 You definitely should specify the default values in the View Model.您绝对应该在视图 Model 中指定默认值。

If you still want to do this in the XAML, you can set the binding mode of the SelectedItem property to OneWayToSource .如果你仍然想在 XAML 中这样做,你可以将SelectedItem属性的绑定模式设置为OneWayToSource In this case, Selectedxy will be updated when SelectedItem changes, but not the other way around.在这种情况下, Selectedxy将在SelectedItem更改时更新,但反之则不会。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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