无法设置表达式。它被标记为“不可共享”并且已被使用

时间:2013-05-27 16:46:09

标签: wpf custom-controls itemssource

iv'e创建了一个从ItemsControl派生的自定义控件。

public class CustsomItemsControl : ItemsControl
{ }

XAML:

  <local:CustsomSelectorControl ItemsSource="{Binding People}"> 
        <local:CustsomSelectorControl.ItemTemplate>
            <DataTemplate>
                <TextBox Text="{Binding Name}"/>                  
            </DataTemplate>
        </local:CustsomSelectorControl.ItemTemplate>
    </local:CustsomSelectorControl>     

控制模板:

<Style TargetType="{x:Type local:CustsomItemsControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:CustsomItemsControl}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}">
                    <ItemsPresenter />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
DataContext中的

   public MainWindow()
    {
        InitializeComponent();

        People = new ObservableCollection<Person>();
        People.Add(new Person("A"));
        People.Add(new Person("B"));
        People.Add(new Person("C"));
    }

    private ObservableCollection<Person> _people;
    public ObservableCollection<Person> People
    {
        get { return _people; }
        set
        {
            _people = value;
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("People"));
        }
    }

项目永远不会被设置,我们用snoop,ItemsSource属性来观察它 在 RED 中标记,但是当我钻研BindingExpression时没有BindingErrors 我得到一个ArgumentExpression:

 Cannot set Expression. It is marked as 'NonShareable' and has already been used.

1 个答案:

答案 0 :(得分:1)

正确设置DataContext

public MainWindow()
{
    InitializeComponent();
    DataContext = this; //This is what you're missing
    ...
}

但是,你需要有一个非常强大的理由来继承ItemsControl