【问题标题】:WPF Data Binding an ObservableCollection (or LinkedList) to a WrapPanelWPF 数据将 ObservableCollection(或 LinkedList)绑定到 WrapPanel
【发布时间】:2013-12-30 12:31:23
【问题描述】:

好的。首先,我在互联网上查看了许多其他问题和大量其他地方关于如何做到这一点,但没有一个有帮助,所以请不要将其标记为重复,而且,请注意,因为我可能犯了一个非常愚蠢的错误。

我正在尝试使用ItemsControlDataTemplateObservableCollection 绑定到WrapPanel。以下是我的 XAML 代码:

<ItemsControl x:Name="wPanel">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <!--<Border BorderBrush="DarkGray" Background="Transparent">-->
                <StackPanel MinWidth="250">
                    <Grid>
                        <TextBlock Text="{Binding address}" />
                    </Grid>
                    <Grid>

                    </Grid>
                </StackPanel>
            <!--</Border>-->
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

注意:我确实有(对于 ItemsControl 的 ItemsSource 属性){Binding properties}

这是我对properties的声明:

public ObservableCollection<Property> properties = new ObservableCollection<Property>();

Property Class 是以下以及更多的属性:

private string address { get; set; }
private string city { get; set; }
private string postcode { get; set; }
private double price { get; set; }
private LinkedList<Tennant> tennants { get; set; }
...

我以为我已经解决了这个问题,

Binding binding = new Binding();
binding.Source = properties;
wPanel.SetBinding(ItemsControl.ItemsSourceProperty, binding);

但是,xaml 中的行:&lt;TextBlock Text="{Binding address}" /&gt; 不起作用。

然后我得出结论,它与属性对象有关,除非我通过代码来绑定,否则它不会绑定。

我做错了什么,因为它没有通过 XAML 等绑定?我需要对属性对象进行哪些更改,或者我需要做什么?

提前致谢。

【问题讨论】:

    标签: c# wpf xaml data-binding properties


    【解决方案1】:

    您可以将 ItemsControl 的 ItemsSource 绑定到属性,就像 @AjS 答案一样。但在此之前,您需要将属性声明更改为属性而不是字段。

    public ObservableCollection<Property> properties { get; set; } 
    

    您的Property 类的地址属性也需要公开。

    public string address { get; set; }
    

    【讨论】:

      【解决方案2】:

      “属性”不是窗口上的属性吗? 如果您在 xaml 中绑定,请确保使用将“属性”声明为“属性”,将窗口的数据上下文设置为自身,然后设置绑定路径:-

               <ItemsControl x:Name="wPanel" ItemsSource="{Binding properties}">
                 this.DataContext=this;  //set datacontext on parent window or control
      

      如果您在代码中执行此操作,直接在 wPanel 上设置 ItemsSource 应该可以:-

                 wPanel.ItemsSource=properties;
      

      【讨论】:

        【解决方案3】:

        这是检查Binding 的简单技巧。每个 WPF 开发人员都必须知道这一点。例如:

        <TextBlock Text="{Binding}" />
        

        跑过去看看。

        如果TextBlock 在 DataContext 中有任何对象,object class name 将显示在 TextBlock 中。 如果DataContext 为空。文本块是Empty

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-12-07
          • 1970-01-01
          • 1970-01-01
          • 2017-09-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多