簡體   English   中英

如何從DataTemplate訪問ListView的ItemsSource中每個對象的屬性路徑

[英]How to access a property path of each object in ItemsSource of a ListView from a DataTemplate

如何從DataTemplate訪問ListView的ItemsSource中每個對象的屬性路徑? 我正在嘗試類似

public class Person : INotifyPropertyChanged
{
    private string _name;
    public string Name
    {
        get {return _name;}
        set
        {
            _name = value;
            OnPropertyChanged();
        }
    }
}

public partial class MyControl : UserControl, INotifyPropertyChanged
{
    private ObservableCollection<Person> _persons;
    public ObservableCollection<Person> Persons
    {
        get {return _persons;}
        set
        {
            _persons = value;
            OnPropertyChanged();
        }
    }
}

<!-- MyControl.xaml.cs -->
<Grid DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}">
    <ListView ItemsSource="{Binding Persons}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Name1" DisplayMemberBinding="{Binding Name}"/>
                <GridViewColumn Header="Name2">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DataContext}"
                                    Text="{Binding Name}" TextAlignMent="Center"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

在MyControl.xaml.cs中,當我在ListView的GridViewColumn中使用DisplayMemberBinding時,可以像Name1一樣直接綁定ItemsSource Persons中每個Person對象的Name屬性。 但是,當我將DataTemplate設置為GridViewColumn以便例如像Name2中那樣手動設置TextAlignMent時,不可能直接訪問ItemsSource Persons中每個Person對象的Name屬性。

如上代碼所示,我通過使用TemplatedParent解決了此問題。 盡管此代碼通常可以正常工作,並且可以達到我的目標,但是VisualStudio在Text =“ {Binding Name}”部分中以消息“無法解析符號”警告我。 有沒有更簡單,更合適的方法來實現這種數據綁定?

您只需綁定到Name屬性

<GridViewColumn.CellTemplate>
     <DataTemplate>
        <TextBlock Text="{Binding Name}" TextAlignment="Center"/>
     </DataTemplate>
</GridViewColumn.CellTemplate>

而且您不需要這樣做:

 <Grid DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}">

DataContext可用於整個樹。

如果您不使用MVVM,則可以在后面的代碼中設置數據上下文:

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

如果您可以正常使用,則“輸出窗口”中的錯誤和警告只是誤報

暫無
暫無

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

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