从ListView控件,XAML绑定对象检索属性/领域 [英] Retrieve properties/fields from binded objects in ListView, XAML
问题描述
我如何检索对象的的ObservableCollection
这是绑定到一个的ListView
?我想说明的属性/在的ListView这些对象的领域
。我使用MVVM设计。在的ListView
是正确的,现在显示绑定的对象的命名空间,只是为了澄清,绑定工作。
How do I retrieve the objects in an ObservableCollection
which is binded to a ListView
? I want to show the properties/fields of these objects in the ListView
. I'm using a MVVM design. The ListView
is right now showing the namespace of the objects binded, just to clarify that the binding works.
在XAML:
<Page
x:Class="Test.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Test"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="using:Test.ViewModels"
mc:Ignorable="d" d:DataContext="{d:DesignInstance vm:TestViewModel}">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Width="400" Height="400">
<Border BorderBrush="Gray" BorderThickness="2">
<ListView x:Name="TestList" ItemsSource="{Binding TestClasses}" Foreground="Black" Height="300">
<!-- Code to bind TestClasses properties/fields goes here -->
</ListView>
</Border>
</Grid>
</Page>
在code背后:
The code behind:
public sealed partial class MainPage : Page
{
private readonly TestViewModel _viewModel;
public MainPage()
{
_viewModel = new TestViewModel();
DataContext = _viewModel;
InitializeComponent();
}
}
我的视图模型:
class TestViewModel : BaseViewModel
{
private ObservableCollection<TestClass> _testClasses;
public ObservableCollection<TestClass> TestClasses
{
get { return _testClasses; }
private set
{
_testClasses = value;
OnPropertyChanged();
}
}
public TestViewModel()
{
TestClasses = new ObservableCollection<TestClass> { new TestClass("test1,", 1), new TestClass("test2", 2) };
}
}
和最后类,我想它的显示属性/字段:
And finally the class of which I would like to show the properties/fields:
[Bindable]
public class TestClass
{
public TestClass(String name, int id)
{
Name = name
Id = id;
}
public String Name { get; set; }
public int Id { get; set; }
}
我认真找不出一个很好的办法做到这一点(我不是有意在视图模型本身的每一个可能的属性/字段绑定) - 我希望你们能帮助
I seriously can't figure out a nice way to do this (I'm not interested in binding every possible property/field in the ViewModel itself) - I hope you guys can help!
推荐答案
那你试试?
因为如果你定义为ListView控件您只需绑定到这样的那些属性一个ItemTemplate:
What did you try? Because if you define an ItemTemplate for that ListView you just bind to those properties like this:
<ListView>
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text={"Binding Name, Mode=TwoWay"} />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
这篇关于从ListView控件,XAML绑定对象检索属性/领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!