簡體   English   中英

WPF數據綁定無法通過XAML起作用(僅通過代碼)

[英]WPF databinding not working via XAML (Only via code)

當試圖結合一個ListViewObservableCollection經由XAML ,所述ListView不被更新並且最初裝載有空白值。

通過XAML

History.xaml.cs

DataContext = this;

History.xaml:

<ListView x:Name="lvHistory" ItemsSource="{Binding Source=history}" BorderThickness="0" Margin="0,0,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="2" util:GridViewSort.AutoSort="True" SizeChanged="lvHistory_SizeChanged">

通過CODE

通過代碼進行綁定時,綁定可以正常工作。

歷史記錄

<ListView x:Name="lvHistory" BorderThickness="0" Margin="0,0,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Column="2" util:GridViewSort.AutoSort="True" SizeChanged="lvHistory_SizeChanged">

History.xaml.cs

DataContext = this;
lvHistory.ItemsSource = history;

通過簡單地通過代碼添加ItemsSource並在XAML中將其刪除,代碼即可正常工作。 我想念什么? 如何通過純XAML創建綁定?

歷史:

public ObservableCollection<LocateElement> history { get; private set; }

用於更新列表的代碼:

    public void Update()
    {
        if (updater.IsBusy) updatePending = true;
        else
        {
            searchValue = txtSearch.Text.Trim();
            updatePending = false;
            updater.RunWorkerAsync();
        }
    }

    private void updateContent(object sender, DoWorkEventArgs e)
    {
        try
        {
            Globals.Variables.logger.Info("Locate History: Updating");

            using (var db = new Data.DataManager())
            {
                var history = db.LocateHistory.Where(o => o.ReceivedBy == Globals.Variables.loginDetails.UserID);

                e.Result = filterResults(history);
            }

        }
        catch (Exception er)
        {
            Globals.Variables.logger.Error(er);
        }
    }

    private void updateFinished(object sender, RunWorkerCompletedEventArgs e)
    {
        List<LocateElement> r = (List<LocateElement>)e.Result;

        history.Clear();
        foreach (LocateElement l in r)
        {
            history.Add(l);
        }

        if (updatePending) Update();
        //else Wpf.Util.GridViewSort.ReapplySort(lvHistory);
    }

    private List<LocateElement> filterResults(IQueryable<LocateElement> list)
    {
        List<LocateElement> history = new List<LocateElement>();

        foreach (LocateElement l in list)
        {
            if (searchValue != "")
            {
                // Use the parameters to filter the results.
                Regex reg = new Regex(WildcardToRegex(searchValue));


                if (reg.IsMatch(l.Serial) || reg.IsMatch(l.Asset) || reg.IsMatch(l.DeviceType) || reg.IsMatch(l.Company) || (l.ReceivedFrom != null && reg.IsMatch(l.ReceivedFrom.Name)) || (l.ReceivedTo != null && reg.IsMatch(l.ReceivedTo.Name)) || reg.IsMatch(l.Row) || reg.IsMatch(l.Shelf) || reg.IsMatch(l.Bin) || reg.IsMatch(l.DateReceived.ToString()))
                {
                    history.Add(l);
                }
            }
            else
            {
                history.Add(l);
            }
        }

        return history;
    }

將數據分配給歷史記錄集合時,需要確保引發屬性更改事件。

例如:

    public class MyViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private ObservableCollection<LocateElement> _history;

        public ObservableCollection<LocateElement> history 
        {
            get { return _history; }
            set
            {
                if (_history != value)
                {
                    _history = value;

                    RaisePropertyChanged("history");
                }
            }
        }

        public MyViewModel()
        {
            _history = new ObservableCollection<LocateElement>();
        }

        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

BindingSource屬性並不意味着您認為的含義。 請改用Path或假設您正在談論Path (默認值)。 這應該做。

<ListView ItemsSource="{Binding history}"  ...>

此外,如果要在構造函數之外設置 history屬性,則需要通知屬性已更改。 如果只在構造函數中設置它,則不需要,但您可能希望使其由readonly字段(而不是自動獲取/設置器)支持。 (TrueEddie的解決方案描述了此問題,並提供了能夠交換實際變量的解決方案)。

暫無
暫無

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

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