簡體   English   中英

在 WPF 中使用 ListView 的 GridView 時訪問單元格文本

[英]Accessing cell text when using the GridView of a ListView in WPF

目前,我真的在為 WPF ListView 苦苦掙扎,我想我錯過了一些非常愚蠢的東西,但經過幾個小時的谷歌搜索后,我最好問問。

我正在嘗試訪問使用 GridView 創建的 ListView 中各個單元格的文本內容,因此:

<ListView Name="MyListView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Foo" DisplayMemberBinding="{Binding Foo}"/>
            <GridViewColumn Header="Bar" DisplayMemberBinding="{Binding Bar}"/>
        </GridView>
    </ListView.View>
</ListView>

我這樣添加到列表視圖中:

var foobars = new ObservableCollection<Foobar>();
foobars.Add(new Foobar { Foo = "Hello", Bar = "world" });
MyListView.ItemsSource = foobars;

現在我想從第一行的第二列中獲取“世界”這個詞。 如果這是 WinForms,我會輸入:

var word = (string)(((ListViewItem)MyListView.Items[0]).SubItems[1]);

我在 WPF 中找不到任何方法:我意識到我可以做到:

var word = ((Foobar)MyListView.Items[0]).Bar;

但在我的實際應用程序中,ListView 中顯示的文本已通過基於它所在列的幾個 ValueConverters 之一,因此與綁定 object 中的文本不同。 我只需要獲取顯示給用戶的文本,而不是底層數據 object。

這里的任何代碼大師有什么建議嗎?

干杯,

加文

好的,找到了一個丑陋的方法來做到這一點。 這是從第一行第二列單元格中獲取“世界”的代碼:

var columns = ((GridView) MyListView.View).Columns;
var foobar = (Foobar)MyListView.Items[0];
var result = (string)DataBinder.Eval(foobar, (Binding) columns[0].DisplayMemberBinding);

這是使用一個助手 class (感謝http://social.expression.microsoft.com/Forums/en-US/wpf/thread/315d2442-b978-4e5f-89cd-1004a51f30的頭發被拉了很多):

public class DataBinder
{
    private static readonly DependencyProperty BindingEvalProperty = DependencyProperty.RegisterAttached(
        "BindingEval",
        typeof(Object),
        typeof(DependencyObject),
        new UIPropertyMetadata(null));

    public static Object Eval(Object data, Binding binding)
    {
        var newbinding = new Binding {Path = binding.Path, Converter = binding.Converter, Source = data};
        var evalobj = new DependencyObject();
        BindingOperations.SetBinding(evalobj, BindingEvalProperty, newbinding);
        return evalobj.GetValue(BindingEvalProperty);
    }
}

因此,這是從第二列中獲取綁定 object 並根據與第一行關聯的數據 object 對其進行評估,其方式與底層 GridView 代碼相同。 這適用於我的應用程序,但如果有人有更簡潔的解決方案,請隨時發布答案!

暫無
暫無

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

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