簡體   English   中英

綁定在WPF窗口用戶控件中不起作用

[英]Bindings not working in WPF window user control

我有此用戶控件XAML:

<Window x:Class="MyProj.Dialog"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:shell="http://schemas.microsoft.com/winfx/2006/xaml/presentation/shell"
        mc:Ignorable="d">

    <Grid>
        <ItemsControl ItemsSource="{Binding Foos}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="ASd" />
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>

</Window>

以及后面的相應代碼:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Effects;
using System.Windows.Threading;

namespace MyProj
{
    public partial class Dialog : Window
    {
        public Dialog() : base()
        {
            InitializeComponent();

            //DataContext = this;
        }

        public ObservableCollection<string> Foos = new ObservableCollection<string> { "foo", "bar" };
    }
}

我遇到的問題是,由於某種原因, ItemsControl不顯示任何內容。 奇怪的是,我什至沒有在輸出中得到綁定警告。

在WPF中,綁定的Path組件只能引用屬性(或屬性路徑),而不能引用字段。 嘗試將集合封裝在屬性中:

private ObservableCollection<string> foos = 
    new ObservableCollection<string> { "foo", "bar" };

public ObservableCollection<string> Foos
{
    get { return foos; }
}

另外,您需要取消注釋設置DataContext

DataContext = this;

您還可以綁定字段(最簡單的方法是命名組件,但需要以某種方式引用它):

<ItemsControl ItemsSource="{Binding}" Name="myItems">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

private ObservableCollection<string> Foos = 
  new ObservableCollection<string> { "foo", "bar" };

public Dialog() : base
{
    InitializeComponent();
    myItems.DataContext = Foos;
}

這比在XAML中對綁定進行硬編碼更為靈活,因為您不是綁定到類的特定屬性,而是綁定到任何公開正確屬性的對象。 假設您有許多集合,則只需將其DataContext(以編程方式)更改為希望顯示的任何集合,就可以輕松地在ItemsControl中顯示其中的任何一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM