简体   繁体   English

将属性绑定到自定义ItemTemplate

[英]Binding property to a custom ItemTemplate

I have a ListView and a custom ItemTemplate (MyUserControl1). 我有一个ListView和一个自定义ItemTemplate(MyUserControl1)。

<ListView Name="listView" HorizontalAlignment="Left" Height="454" Margin="656,147,0,-461" VerticalAlignment="Top" Width="337">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel Grid.Column="1" VerticalAlignment="Top" Margin="10,0,0,0">
                <TextBlock Text="{Binding text}" Style="{StaticResource CaptionTextStyle}" TextWrapping="NoWrap"/>
                <local:MyUserControl1 MyParagraph="{Binding paragraph}"></local:MyUserControl1>
                <TextBlock Text="test" Style="{StaticResource CaptionTextStyle}" TextWrapping="NoWrap"/>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

The MyUserControl1.cs only includes a property (MyParagraph): MyUserControl1.cs仅包含一个属性(MyParagraph):

public Paragraph MyParagraph
{
    get 
    { 
        return _MyParagraph; 
    }
    set 
    {
        _MyParagraph = value;
        Paragraph paragraph = new Paragraph();

        for (int i = 0; i < _MyParagraph.Inlines.Count; i++)
        {
            paragraph.Inlines.Add(_MyParagraph.Inlines[i]);
            richTextBlock.Blocks.Add(paragraph);
        }
    }
}

The error I am getting is: 我得到的错误是:

Failed to assign to property 'App4.MyUserControl1.MyParagraph'. 无法分配给属性“ App4.MyUserControl1.MyParagraph”。

I have migrated from Flex so I am doing something wrong but I have no idea where. 我已经从Flex迁移,所以我做错了事,但是我不知道在哪里。

In order to bind data, the target property must be a DependancyProperty, so in order to make this binding work, MyParagraph should be a dependancyproperty in your UserControl like below 为了绑定数据,目标属性必须是DependancyProperty,因此,为了使此绑定起作用, MyParagraph应该是UserControl中的MyParagraph ,如下所示

 public Paragraph MyParagraph
  {
    get { return (Paragraph)this.GetValue(MyParagraphProperty); }
    set { this.SetValue(MyParagraphProperty, value); } 
  }
  public static readonly DependencyProperty MyParagraphProperty = DependencyProperty.Register(
    "MyParagraph", typeof(Paragraph), typeof(UserControl1),new PropertyMetadata(null));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM