【问题标题】:Binding property to a custom ItemTemplate将属性绑定到自定义 ItemTemplate
【发布时间】:2013-10-09 00:30:53
【问题描述】:

我有一个 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>

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);
        }
    }
}

我得到的错误是:

未能分配给属性“App4.MyUserControl1.MyParagraph”。

我已从 Flex 迁移,所以我做错了,但我不知道在哪里。

【问题讨论】:

    标签: c# wpf listview binding itemtemplate


    【解决方案1】:

    为了绑定数据,目标属性必须是一个 DependancyProperty,所​​以为了使这个绑定工作,MyParagraph 应该是你的 UserControl 中的一个依赖属性,如下所示

     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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-03
      • 2011-05-22
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      相关资源
      最近更新 更多