简体   繁体   English

有没有办法在 MahApps.Metro Flyout 中设置 ComboBox 的 SelectedIndex?

[英]Is there a way to set SelectedIndex of a ComboBox inside a MahApps.Metro Flyout?

I have a UserControl that is contained in a MahApps.Metro.Controls.Flyout .我有一个包含在MahApps.Metro.Controls.Flyout中的UserControl Inside that UserControl , there is a ComboBox .在那个UserControl里面,有一个ComboBox I'm trying to set the default SelectedIndex to 0. So that when the flyout is opened, the first item ("Source A") is selected.我正在尝试将默认的SelectedIndex设置为 0。这样,当打开浮出控件时,会选择第一项(“源 A”)。

Currently, whenever the flyout is opened, the SelectedIndex is being set to -1 and nothing is selected.目前,每当打开浮出控件时, SelectedIndex都会设置为 -1,并且不会选择任何内容。

View that holds the Flyout:持有 Flyout 的视图:

<mah:FlyoutsControl>
    <mah:Flyout IsOpen="{Binding MyViewIsOpen, Mode=TwoWay, 
    UpdateSourceTrigger=PropertyChanged}"
    x:Name="DataSourceFlyout">
        <Grid>
            <local:DataSourceView/>
        </Grid>
    </mah:Flyout>
</mah:FlyoutsControl>

DataSourceView:数据源视图:

<UserControl ...>
    <ComboBox SelectedIndex="0" 
      SelectedValue="{Binding SelectedDataSource, Mode=TwoWay, 
      UpdateSourceTrigger=PropertyChanged}"
      SynchronizedWithCurrentItem="True">
        <ComboBoxItem Tag="SourceA" Content="Source A"/>
        <ComboBoxItem Tag="SourceB" Content="Source B"/>
        <ComboBoxItem Tag="SourceC" Content="Source C"/>
    </ComboBox>
</UserControl>

ViewModel:视图模型:

public string SelectedDataSource { get; set; }

Note: This seems to be caused by my UserControl being within a Flyout .注意:这似乎是由于我的UserControlFlyout中引起的。 The same XAML works fine when used outside of a Flyout .Flyout之外使用时,相同的 XAML 工作正常。 Is there something else I need to do to get the first item selected in my ComboBox ?我还需要做些什么才能在我的ComboBox中选择第一个项目吗?

The source property in the view model determines the value to be selected.视图 model 中的源属性确定要选择的值。

It's unclear what the value of the SelectedDataSource property is in your example but you should set it to either "SourceA", "SourceB" or "SourceC" and then set the SelectedValuePath property to "Tag":在您的示例中不清楚SelectedDataSource属性的值是什么,但您应该将其设置为“SourceA”、“SourceB”或“SourceC”,然后将SelectedValuePath属性设置为“Tag”:

<ComboBox SelectedValue="{Binding SelectedDataSource, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
          SelectedValuePath="Tag">
    <ComboBoxItem Tag="SourceA" Content="Source A"/>
    <ComboBoxItem Tag="SourceB" Content="Source B"/>
    <ComboBoxItem Tag="SourceC" Content="Source C"/>
</ComboBox>

View Model:查看 Model:

public string SelectedDataSource { get; set; } = "SourceA";

If you intend to specify the selected value in the view using the SelectedIndex property, you should remove the binding.如果您打算使用SelectedIndex属性在视图中指定选定的值,则应删除绑定。

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

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