簡體   English   中英

將ListBox的ItemsSource設置為包含類的屬性

[英]Setting ItemsSource of ListBox to a property of it's containing class

我有以下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>  

以及代碼隱藏 -

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; }
    }
}  

我想將NameList設置為來自xaml的ListBox的ItemsSource而不是來自代碼隱藏。 我怎么做?

編輯:我知道MVVM這樣做的方式。 但這不是我要問的。

編輯:這不是我不喜歡MVVM左右。 在做一些快速測試時我才意識到我不知道該怎么做。 所以,想知道是否可能,並試圖學習。 無論如何使用StaticResource

如果你的意思是“不做MVVM方式”,你不想使用ViewModels,那么你可以通過以下步驟數據綁定到“codebehind”:

在XAML中設置綁定:

<ListBox ItemSource="{Binding NameList}"/>

並設置DataContextthis你已經在人口列表如后Window_Loaded事件:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    _nameList = new List<string>
                    {
                        "X",
                        "Y",
                        "Z"
                    };
    DataContext = this;
}

編輯:如果您不想設置DataContext ,可以直接綁定到窗口:

<Window Name="window" ... />

  <ListBox  ItemsSource="{Binding NameList, ElementName=window}"/>

或者您可以使用AncestorBinding作為

<ListBox ItemsSource="{Binding NameList, RelativeSource={RelativeSource AncestorType=Window}}"/>

但是,在這兩種情況下,列表都將為空,因為您在加載的事件中填充了列表這一事實不會通知視圖。 因此,您需要使用INPC通知"NameList"屬性已更改。

暫無
暫無

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

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