将Tab控件ItemSource中的项绑定到用户控件DependencyProperty

时间:2018-01-08 22:26:54

标签: c# wpf binding

我有一个从对象列表和WPF用户控件创建的选项卡控件,我想直接与其中一个对象关联。我将此关联创建为控件中的依赖项属性。

我得到的绑定错误是:

System.Windows.Data Error: 1 : Cannot create default converter to perform 'one-way' conversions between types 'WPFTester.Control' and 'WPFTester.TestClass'. Consider using Converter property of Binding. BindingExpression:Path=; DataItem='Control' (Name=''); target element is 'Control' (Name=''); target property is 'ClassDependency' (type 'TestClass')

似乎它改变了主意在绑定之前datacontext是什么。

主窗口创建对象列表并将它们附加到选项卡控件。我在这里讨论绑定到Control Dependency Object的问题。

XAML:

<Grid>
    <TabControl ItemsSource="{Binding Classes}">
        <TabControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Title}"/>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate>
                <local:Control ClassDependency="{Binding}"/>
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>
</Grid>

Code-Behind:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private BindingList<TestClass> classes;

    public event PropertyChangedEventHandler PropertyChanged;

    public BindingList<TestClass> Classes
    {
        get { return classes; }
        set
        {
            classes = value;
            PropertyChanged?.Invoke(this, new 
            PropertyChangedEventArgs("Classes"));
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;

        Classes = new BindingList<TestClass>
        {
            new TestClass() { Title = "123", Content="abc" },
            new TestClass() { Title = "456", Content="def" }
        };
    }

其他课程很简单,我不认为问题在于他们,但无论如何我都会提供。

数据类很简单:

    public class TestClass
{
    public string Title { get; set; }
    public string Content { get; set; }
}

用户控件显示绑定值和常量值。它还提供了一个依赖属性。

XAML:

<StackPanel>
    <TextBlock Text="{Binding TextDependency}" Margin="5"/>
    <TextBlock Text="I'm here"/>
</StackPanel>

Code-Behind:

public partial class Control : UserControl
{
    public static readonly DependencyProperty ClassDependencyProperty = 
        DependencyProperty.RegisterAttached(
        "ClassDependency",
        typeof(TestClass),
        typeof(Control));

    public TestClass ClassDependency
    {
        get { return (TestClass)GetValue(ClassDependencyProperty); }
        set { SetValue(ClassDependencyProperty, value); }
    }

    public Control()
    {
        InitializeComponent();
        this.DataContext = this;
    }
}

0 个答案:

没有答案