WPF ComboBox不会在初始化时触发事件

时间:2017-10-11 11:58:32

标签: c# wpf xaml combobox

我有以下情况: 1.我有Window Load事件 - 它获取ComboBox的SourceItems 2. ComboBox具有更改选择的EventTrigger和以下XAML:

    <ComboBox x:Name="uxEnvironmentsComboBox" 
         ItemsSource="{Binding Environments}" Width="90" Margin="0,10,160,0" 
         HorizontalAlignment="Right"  
         VerticalContentAlignment="Center" 
         HorizontalContentAlignment="Center"
         IsSynchronizedWithCurrentItem="True" SelectedIndex="0">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="SelectionChanged">
                            <i:InvokeCommandAction Command="{Binding SelectEnvironment}"
                                                   CommandParameter="{Binding Path=SelectedItem, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ComboBox}}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </ComboBox>

一切正常,窗口加载正确,列表填充在ComboBox中,但是当进行默认选择时,我的<i:EventTrigger EventName="SelectionChanged">不会触发,除非我制作手册,否则不会触发其余的应用程序配置选择改变?!

1 个答案:

答案 0 :(得分:0)

SelectEnvironment应该是您绑定到的属性:

<ComboBox x:Name="uxEnvironmentsComboBox" 
         ItemsSource="{Binding Environments}" Width="90" Margin="0,10,160,0" 
         SelectedItem="{Binding SelectEnvironment}"
         HorizontalAlignment="Right"  
         VerticalContentAlignment="Center" 
         HorizontalContentAlignment="Center"
         IsSynchronizedWithCurrentItem="True" SelectedIndex="0">
</ComboBox>

如果您愿意,可以在此属性的setter中调用任何命令:

private Environment _selectEnvironment;
public Environment SelectEnvironment
{
    get { return _selectEnvironment; }
    set
    {
        _selectEnvironment = value;
        //invoke command
        YourCommand.Execute(_selectedEnvironment);
    }
}

如果您想最初调用命令或设置属性,您可以在视图模型的构造函数中执行此操作。您无需使用InvokeCommandAction