我試圖將列表視圖的索引綁定到列表中的一列用於顯示目的。WPF:無法解析資源「IndexConverter」
最後,我還希望能夠使用行的DataTemplate中的「刪除」按鈕刪除條目,但獲取綁定工作是第一步。
本(或某些變化)似乎是最受歡迎的答案之一: How to display row numbers in a ListView?
這是我到目前爲止有: XAML:
<GridViewColumn Header="Index" DisplayMemberBinding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}, Converter={StaticResource IndexConverter}}">
</GridViewColumn>
C#:
public class IndexConverter : IValueConverter
{
public object Convert(object value, Type TargetType, object parameter)
{
ListViewItem item = (ListViewItem)value;
ListView listView = ItemsControl.ItemsControlFromItemContainer(item) as ListView;
int index = listView.ItemContainerGenerator.IndexFromContainer(item);
return index.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter)
{
throw new NotImplementedException();
}
}
我把這個函數放在我的應用程序視圖的CS文件中。
它告訴我它無法解析IndexConverter的資源。我覺得這可能是一個快速解決方案,而且我已經將該功能放在了錯誤的位置,或者我缺少添加資源的一些代碼。但是,鏈接中的解決方案並未將其清除。
UPDATE:
基於sa_ddam213的建議,我已經編輯我的App.xaml文件包含此:
<Application x:Class="WpfApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:myConverters="clr-namespace:WpfApplication1.Views"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary Source="Themes/DarkTheme.xaml" />
<myConverters:IndexConverter x:Key="IndexConverter" />
</Application.Resources>
</Application>
現在我得到一個錯誤,指出資源只能設置一旦。評論出DarkTheme消除了這個錯誤,但它接着說IndexConverter不存在於WpfApplication1.Views命名空間中,這絕對是我放置它的地方。
你可以顯示xaml在哪裏添加轉換器到您的資源 – 2014-09-03 00:55:40
@ sa_ddam213:這不是我做的。這基本上是我問的 - 如何添加它以及它的位置。 – 2014-09-03 17:16:37