0

所以,我可能会以错误的方式解决这个问题,但我认为无论如何它都应该起作用。我有一个 ListBox 从数据库中加载它的项目。

<UserControl.Resources>
    <DataTemplate x:Key="DataTemplateListBox">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="60" />
                <ColumnDefinition Width="130" />
            </Grid.ColumnDefinitions>

            <CheckBox Grid.Column="0" x:Name="cbNonFat" VerticalAlignment="Center" Margin="14,0,10,0" IsChecked="{Binding IsNonFat, Mode=TwoWay}">
            </CheckBox>

            <ComboBox HorizontalAlignment="Left" Width="120" Grid.Column="4" Name="cbbSeason"  Margin="0,0,10,0" Tag="{Binding Season, Mode=TwoWay}" Loaded="cbbSeason_Loaded" SelectionChanged="cbbSeason_SelectionChanged">
                <ComboBoxItem Content="Year Round" Tag="0"/>
                <ComboBoxItem Content="Spring/Summer" Tag="1"/>
                <ComboBoxItem Content="Fall/Winter" Tag="2"/>
                <ComboBoxItem Content="Featured" Tag="3"/>
            </ComboBox>

        </Grid>
    </DataTemplate>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
    <ListBox Name="lbFlavors" ItemTemplate="{StaticResource DataTemplateListBox}"/>
</Grid>

在代码隐藏中,我将 Tag 更改为 Selected Index:

    private void cbbSeason_Loaded(object sender, RoutedEventArgs e)
    {
        foreach (ComboBoxItem cbi in (sender as ComboBox).Items)
        {
            if (cbi.Content.ToString() == (sender as ComboBox).Tag.ToString())
            {
                (sender as ComboBox).SelectedIndex = Convert.ToInt16(cbi.Tag);
                break;
            }
        }
    }

Then, when the selection is changed, I update the Tag:

    private void cbbSeason_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        (sender as ComboBox).Tag = (cbbSeason.SelectedItem as ComboBoxItem).Content.ToString();
    }

当我将更改保存回数据库时,复选框更改成功,但组合框不成功。如果我在 cbbSeason_SelectionChanged 事件上设置断点,则标签根本不会更新,所以显然这就是问题所在,但我不知道为什么它没有更新。

4

0 回答 0