[英]Setting ItemsSource of ListBox to a property of it's containing class
I have the following xaml - 我有以下xaml -
<Window x:Class="DataTemplateTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="400" Width="600" Loaded="Window_Loaded">
<Grid>
<ListBox Height="380" Margin="10,12,0,0" Width="355"/>
</Grid>
</Window>
and the following code-behind - 以及代码隐藏 -
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
_nameList = new List<string>
{
"X",
"Y",
"Z"
};
}
private List<string> _nameList;
public List<string> NameList
{
get { return _nameList; }
}
}
I want to set the NameList
as the ItemsSource
of the ListBox from the xaml, not from the code-behind. 我想将
NameList
设置为来自xaml的ListBox的ItemsSource
, 而不是来自代码隐藏。 How do I do that? 我怎么做?
EDIT : I know the MVVM-way of doing this. 编辑:我知道MVVM这样做的方式。 But that's not what I'm asking.
但这不是我要问的。
EDIT : It's not that I don't like MVVM or so. 编辑:这不是我不喜欢MVVM左右。 While doing some quick test I just realized that I don't know how to do this.
在做一些快速测试时我才意识到我不知道该怎么做。 So, wondering if it's possible, and trying to learn.
所以,想知道是否可能,并试图学习。 Is it anyhow possible using
StaticResource
? 无论如何使用
StaticResource
?
If you've meant on "not doing the MVVM-way" that you don't want to use ViewModels then you can data-bind to the "codebehind" with the following steps: 如果你的意思是“不做MVVM方式”,你不想使用ViewModels,那么你可以通过以下步骤数据绑定到“codebehind”:
Set the binding in XAML: 在XAML中设置绑定:
<ListBox ItemSource="{Binding NameList}"/>
And set the DataContext
to this
after you have populated your list eg in the Window_Loaded
event: 并设置
DataContext
到this
你已经在人口列表如后Window_Loaded
事件:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
_nameList = new List<string>
{
"X",
"Y",
"Z"
};
DataContext = this;
}
Edit: If you don't want to set the DataContext
you can bind directly to the window: 编辑:如果您不想设置
DataContext
,可以直接绑定到窗口:
<Window Name="window" ... />
<ListBox ItemsSource="{Binding NameList, ElementName=window}"/>
Or you can use AncestorBinding as 或者您可以使用AncestorBinding作为
<ListBox ItemsSource="{Binding NameList, RelativeSource={RelativeSource AncestorType=Window}}"/>
However I both cases the list will be empty because the view won't be notified by the fact that you populated your list in the loaded event. 但是,在这两种情况下,列表都将为空,因为您在加载的事件中填充了列表这一事实不会通知视图。 So you need to use INPC to notify that the
"NameList"
property changed. 因此,您需要使用INPC通知
"NameList"
属性已更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.