簡體   English   中英

WPF自定義控件數據綁定

[英]WPF custom control databinding

我是WPF中自定義控件開發的新手,但是我嘗試開發一個用於正在開發的應用程序中的控件。 此控件是一個自動完成的文本框。 在此控件中,我有一個DependencyProprety ,其中包含可能的條目的列表,以便人們在輸入文本時可以選擇

public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource",typeof (IList<object>),typeof (AutoCompleteTextBox),new PropertyMetadata(null));
        public IList<object> ItemsSource
        {
            get { return (IList<object>) GetValue(ItemsSourceProperty); }
            set
            {
                SetValue(ItemsSourceProperty, value);
                RaiseOnPropertyChanged("ItemsSource");
            }
        }

我在用戶控件中使用此控件,並將此控件與viewmodel中的屬性相關聯

<CustomControls:AutoCompleteTextBox Height="23" Width="200" 
        VerticalAlignment="Center" Text="{Binding Path=ArticleName, Mode=TwoWay,                  
        UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding Path=Articles, 
        Mode=OneWay, UpdateSourceTrigger=PropertyChanged}">
</CustomControls:AutoCompleteTextBox>

我有一個在用戶控件負載上分配給用戶控件負載的數據上下文的視圖模型

protected virtual void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                this.DataContext = viewModel;
                SetLabels();
            }
        }

當我嘗試在用戶輸入一些文本后在列表中進行搜索時,此視圖模型具有帶有值的屬性Articles ,但控件的ItemsSource屬性為null。 創建控件時是否錯過了任何特殊步驟,因此請使用mvvm模式。

我希望以一種可以理解的方式解釋問題。 任何幫助/提示都將受到歡迎。

這里有兩個問題:

首先,您的dependency屬性是將該屬性的“默認”值定義為null。 您可以通過更改元數據以指定新集合來更改此設置:

public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource",typeof (IList<object>),typeof (AutoCompleteTextBox),
     new PropertyMetadata(new List<object>));

其次,在使用依賴項屬性時,設置器不能包含任何邏輯。 您應該將屬性設置為:

   public IList<object> ItemsSource
    {
        get { return (IList<object>) GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }

這是因為綁定器實際上不會調用綁定器-僅在使用代碼時才調用。 但是,由於該類是DependencyObject且這是一個DP,因此不需要引發屬性更改的事件。

暫無
暫無

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

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