如何绑定从文件加载的ComboBox?

时间:2012-09-05 20:54:03

标签: wpf binding combobox

这是我的情况。我在画布中有多个用户控件。使用XamlWriter将此画布保存到xaml文件中。正如大多数人所知,使用此方法不会保存绑定,因此当我使用XamlReader并重新读取用户控件时,绑定不再存在。

对于一个简单的测试,我一直在尝试重新绑定从XAML文件加载的ComboBox ItemsSource(这是我在用户控件中遇到的问题)。我尝试过实现INotifyPropertyChanged,但我的变量是:

public event PropertyChangedEventHandler PropertyChanged
当我尝试设置ComboItemsProperty时,

始终为null:

public ObservableCollection<string> ComboItemsProperty
{
    get { return ComboItems; } //Field
    set 
    {
        ComboItems = value;
        OnPropertyChanged("ComboItemsProperty");
    }

因此,我的最终目标是加载一个xaml文件,然后将项目添加到ComboBox的ItemsSource中,然后使用新项目更新ComboBox。

我是以错误的方式来做这件事的吗?有人能为我提供一个简单的工作示例吗?

编辑:

protected void OnPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged
    if (PropertyChanged != null)
    {
         handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

我很确定它与加载XAML有关,而且不再设置绑定。我试过设置绑定,但没有运气。

第二次编辑:

我认为我99%确定绑定是原因。只要我没有从文件中加载组合框,我的OnPropertyChanged就可以正常工作。我尝试按如下方式设置绑定:

Binding bind = new Binding();
bind.Mode = BindingMode.TwoWay;
bind.Source = this.ComboItemsProperty; //Not sure about this line.
bind.Path = new PropertyPath("ComboItemsProperty");
this.SetBiding(ComboBox.ItemsSourceProperty, bind);

确认。当我带回一个简单的组合框时,我试图绑定它是不行的。它必须是上面代码中的内容。

1 个答案:

答案 0 :(得分:0)

bind.Source需要指向包含ComboItemsProperty的对象,而不是属性本身。

Binding bind = new Binding();
bind.Mode = BindingMode.TwoWay;
bind.Source = this;
bind.Path = new PropertyPath("ComboItemsProperty");
this.SetBiding(ComboBox.ItemsSourceProperty, bind);

您可以通过以下方式检查绑定是否成功:

 if (GetBindingExpression(ComboBox.ItemsSourceProperty).Status != BindingStatus.Active)
 { 
    //binding didn't work
 }
相关问题