簡體   English   中英

ComboBox ItemsSource綁定不會隨着Observable Collection Add更新

[英]ComboBox ItemsSource binding doesn't update with Observable Collection Add

我有一個簡單的wpf應用程序,我想嘗試使用xaml的ItemsSource綁定。 當我單擊按鈕時。 還應該在用戶界面中對其進行更新,但事實並非如此。

為什么不起作用?

XAML代碼:

<Window x:Class="SendRawEthernetPacketsGUI.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
<Grid>
    <ComboBox HorizontalAlignment="Left" Margin="76,65,0,0" VerticalAlignment="Top" Width="120" ItemsSource="{Binding test}"/>
    <Button Content="Button" HorizontalAlignment="Left" Margin="90,171,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>

</Grid>

C#代碼:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace SendRawEthernetPacketsGUI
{

/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
    public ObservableCollection<string> test = new ObservableCollection<string>();
    public Window1()
    {
        InitializeComponent();
        DataContext = this;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        test.Add("fdfddf");
    }
}
}

甚至問這個問題也有點愚蠢,但是即使在Google中尋找也沒有幫助。 那可以嗎

首先,您的綁定從未起作用。 您只能綁定到屬性,而不能綁定到fields

嘗試以下方法:

public ObservableCollection<string> test { get; set; }

public Window1()
{
    Test = new ObservableCollection<string>();
}

或者,如果您想要一些棘手的C#6魔術:

public ObservableCollection<string> test => new ObservableCollection<string>();

這是一個函數成員,並編譯為一個只讀屬性,該屬性已初始化為新的ObservableCollection

注意事項/設計錯誤:

請注意,在兩種情況下,您都不會使用INotifyPropertyChanged ,因此UI不會接管該集合的批發分配。 您還應該將PascalCase用於公共屬性,並使用適當的視圖模型而不是綁定到背后的代碼。

暫無
暫無

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

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