【问题标题】:WPF custom control databindingWPF 自定义控件数据绑定
【发布时间】:2011-03-23 17:23:58
【问题描述】:

我是在 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");
            }
        }

我在用户控件中使用此控件并将此控件与视图模型中的属性相关联

<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 属性为空。 我在创建控件时是否遗漏了任何特殊步骤,因此请使用 mvvm 模式。

我希望以一种可以理解的方式解释问题。欢迎任何帮助/提示。

【问题讨论】:

    标签: wpf data-binding mvvm custom-controls


    【解决方案1】:

    这里有两个问题:

    首先,您的依赖属性正在将此属性的“默认”值定义为空。您可以通过更改元数据来指定新集合来更改它:

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

    其次,当使用依赖属性时,setter 不能包含任何逻辑。您应该将您的属性设置为:

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

    这是因为绑定系统实际上并没有调用 setter - 只有当您使用代码时。但是,由于该类是一个 DependencyObject 并且这是一个 DP,因此您不需要引发属性更改事件。

    【讨论】:

    • 现在视图模型中的属性被调用,但是当我调用 wordMatches = ItemsSource.Where(x =&gt; x.ToString().ToLower().StartsWith(Text.ToLower(), StringComparison.InvariantCulture)) .Select(x =&gt; new KeyValuePair&lt;string, object&gt;(x.ToString(), x)).ToList(); 时,ItemsSource 仍然为空
    猜你喜欢
    • 2015-07-07
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 2011-08-06
    相关资源
    最近更新 更多