1

我是编程初学者,尤其是WPF. 我有一个应用程序WPF。我已将与.sdf数据库的连接从更改Entity FrameworkSqlCeCommand。不幸的是,在此之前,我有以下用于绑定 a 的代码ComboBox

<DockPanel Grid.Row="4">
    <Button x:Name="LoadButton" Height="20" ToolTip="Choose setting name to load"    Width="75" Padding="2,2,2,2" Margin="2,0,2,0" HorizontalAlignment="Left" VerticalAlignment="Center" Content="Load Settings"  Command="{Binding LoadSettingsCommand}"/>

    <ComboBox x:Name="LoadSettingsComboBox" ToolTip="Choose setting name to load" ItemsSource="{Binding Mode=OneWay, Path=Settings/}" SelectedValue="{Binding LoadSettingName,  Mode=OneWayToSource}" SelectedValuePath="Name" Grid.Column="1" >
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock HorizontalAlignment="Center" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>
</DockPanel>

和:

List<Setting> _settings;
Settings = new CollectionView(_settings);

它奏效了。更改连接后DataBase没有错误,但ComboBox不显示任何数据。设置类之前由实体框架生成。现在,我制作了自己的班级设置。这个类应该实现什么?你能帮助我吗?

4

1 回答 1

1

如果您觉得有帮助,请投票给这个答案。

根据我的理解,如果您使用设置作为数据对象,则需要将其存储到 ObservableCollection<> 中。像这样使用:

private ObservableCollection<Settings> _settingList = new ObservableCollection<Settings>();
    public ObservableCollection<Settings> SettingList
    {
        get
        {
            return this._settingList;
        }
        set
        {
            if(value==null)
            return;
            this._settingList = value;
            //OnPropertyChanged(()=>this.SettingList); //It is not required as ObservableCollection<> itself notifies on collection changed.
        }
    }

如果您正在实现自己的 Setting 类,那么您应该实现 INotifyPropertyChanged 接口以将属性与组合框项绑定。以下是供您参考的代码:

public class SettingsModel : INotifyPropertyChanged
{
    #region INotifyPropertyChanded event Implementation

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged<TProperty>(Expression<Func<TProperty>> propertyExpression)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (null == handler)
            return;

        if (null != propertyExpression)
        {
            var e = new PropertyChangedEventArgs(((MemberExpression)propertyExpression.Body).Member.Name);
            handler(this, e);
        }
    }

    public void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (null != PropertyChanged)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion
}

上面的实现为您提供了一个方法 OnPropertyChanged(string propertyName)。您需要在类中每个属性的“设置”部分调用此方法。每当属性值发生更改时,它都会通知控件的 DependencyProperty。

希望这会帮助你。

于 2013-05-04T12:29:39.353 回答