以下是WPF应用程序的代码段,其中我正在使用ListView控件和自定义ListView控件,但是在UI中,自定义ListView控件显示了类名,而List View控件则显示了实际数据[即Class1的Text1属性值]。我知道通过覆盖Class1的ToString()可以使我的自定义ListView显示实际数据,但是我不想覆盖ToString()。因此,有没有办法将自定义ListView的模板更改为类似于ListView控件的工作方式?
MainWindow.xaml:
class Animal{
int age;
String type;
public Animal(int age, String type){
this.age = age;
this.type = type;
}
}
public class MainCls{
public static void main(String[] args){
Animal[] arr = {new Animal(2, "Her"), new Animal(3,"Car")};
Arrays.sort(arr);
}
}
MainWindow.xaml.cs
<Window
x:Class="Swip.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:Custom.Controls;assembly=Custom.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Swip"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="525"
Height="350"
mc:Ignorable="d">
<Grid d:DataContext="{d:DesignInstance d:Type=local:MainWindowModel}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="5*" />
<ColumnDefinition Width="5*" />
</Grid.ColumnDefinitions>
<controls:SwipableListView Grid.Column="0" ItemsSource="{Binding Items, Mode=OneWay}">
<controls:SwipableListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn DisplayMemberBinding="{Binding Path=Text1}" Header="11" />
</GridView.Columns>
</GridView>
</controls:SwipableListView.View>
</controls:SwipableListView>
<ListView Grid.Column="1" ItemsSource="{Binding Items, Mode=OneWay}">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn DisplayMemberBinding="{Binding Path=Text1}" Header="11" />
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
ViewModel
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext=new MainWindowModel();
}
}
自定义控件模板
public class MainWindowModel
{
public MainWindowModel()
{
this.Items = new ObservableCollection<Class1>
{
new Class1(1),
new Class1(2),
new Class1(3),
};
this.DeleteCommand = new RoutedCommand("Delete", typeof(MainWindowModel));
}
public ObservableCollection<Class1> Items { get; private set; }
public ICommand DeleteCommand { get; set; }
}
答案 0 :(得分:0)
Clemens建议-通过将ContentPresenter更改为GridViewRowPresenter,可以解决此问题。 请参阅:ListView Styles and Templates