将Combobox值更新到数据库中

时间:2013-03-19 18:11:08

标签: wpf silverlight data-binding combobox

所以,我可能会以错误的方式解决这个问题,但我认为无论如何都应该这样做。我有一个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;
            }
        }
    }

然后,当选择更改时,我更新标签:

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

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

0 个答案:

没有答案