【问题标题】:Two-Way Binding Issue of Unknown Object in WPF Custom Control Dependency PropertyWPF自定义控件依赖属性中未知对象的双向绑定问题
【发布时间】:2016-08-28 03:58:43
【问题描述】:

我有一个自定义控件 - 为自动完成文本框实现。 我从以下问题Create a Custom Control with the combination of multiple controls in WPF C# 中得到了所有想法。在那个自定义控件中,他们建议使用以下代码来添加项目,它可以完美运行并且双向绑定也是如此

(this.ItemsSource as IList<string>).Add(this._textBox.Text);

但是,我把下面的代码改成了Unknown Object,所以我把IList&lt;string&gt;改成了IList&lt;object&gt;

(this.ItemsSource as IList<object>).Add(item);

XAML:

 <local:BTextBox 
            ItemsSource="{Binding Collection}" 
            ProviderCommand="{Binding AutoBTextCommand}" 
            AutoItemsSource="{Binding SuggCollection}" />

但它不会更新 ViewModel 属性 Collection。我也在 xaml 中尝试了以下更改

ItemsSource="{Binding Collection, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"

我不知道我在哪里做错了。

功能CustomControl 中的TextBox 接受来自用户的输入并触发ProviderCommand,该命令根据该命令过滤远程数据用户输入并通过 AutoItemsSource 发送过滤后的集合,此属性绑定为 ItemsSource 中的 ItemsSource 内部 CustomControl 以选择项目。我们可以从ListBoxItem中选择Item,通过点击Item,触发CustomControl类中的AddCommand命令,将选中的项目添加到ItemSource属性中的CustomControl。我在此属性 ItemsSource 中遇到了双向绑定问题。仅从该属性中,我们可以将 Selected 项作为 Collection 获取。

这是我的完整源代码

自定义控件 C# 代码:

public class BTextBox : ItemsControl
{

    static BTextBox()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(BTextBox), new FrameworkPropertyMetadata(typeof(BTextBox)));
    }

    #region Private Members
    private TextBox _textBox;
    private ItemsControl _itemsView;
    #endregion

    #region Dependency Property Private Members
    public static readonly DependencyProperty ProviderCommandProperty = DependencyProperty.Register("ProviderCommand", typeof(ICommand), typeof(BTextBox), new PropertyMetadata(null));
    public static readonly DependencyProperty AutoItemsSourceProperty = DependencyProperty.Register("AutoItemsSource", typeof(IEnumerable<dynamic>), typeof(BTextBox), new PropertyMetadata(null, OnItemsSourceChanged));
    #endregion

    #region Dependency Property Public members
    public IEnumerable<dynamic> AutoItemsSource
    {
        get { return (IEnumerable<dynamic>)GetValue(AutoItemsSourceProperty); }
        set { SetValue(AutoItemsSourceProperty, value); }
    }
    #endregion

    #region Listener Methods
    private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var tb = d as BTextBox;
        if ((e.NewValue != null) && ((tb.ItemsSource as IList<object>) != null))
        {
            (tb.AutoItemsSource as IList<object>).Add(e.NewValue);
        }
    }
    #endregion

    #region Override Methods
    public override void OnApplyTemplate()
    {
        this._textBox = this.GetTemplateChild("PART_TextBox") as TextBox;
        this._itemsView = this.GetTemplateChild("PART_ListBox") as ItemsControl;

        this._textBox.TextChanged += (sender, args) =>
        {
            if (this.ProviderCommand != null)
            {
                this.ProviderCommand.Execute(this._textBox.Text);
            }
        };

        base.OnApplyTemplate();
    }
    #endregion


    #region Command
    public ICommand ProviderCommand
    {
        get { return (ICommand)GetValue(ProviderCommandProperty); }
        set { SetValue(ProviderCommandProperty, value); }
    }

    public ICommand AddCommand
    {
        get
        {
            return new DelegatingCommand((obj) =>
            {
                (this.ItemsSource as IList<object>).Add(obj);
            });
        }
    }
    #endregion
}

Generic.xaml代码是

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SampleControl">
    <Style TargetType="{x:Type local:BTextBox}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:BTextBox}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="40"/>
                                <RowDefinition Height="Auto"/>
                            </Grid.RowDefinitions>
                            <TextBox x:Name="PART_TextBox" Grid.Row="0" Width="*" VerticalAlignment="Center" />
                            <ListBox ItemsSource="{TemplateBinding AutoItemsSource}" Grid.Row="1" x:Name="PART_ListBox_Sugg" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                                <ListBox.ItemTemplate>
                                    <DataTemplate>
                                        <CheckBox IsChecked="{Binding Value.IsChecked}" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:BTextBox}}, Path=AddCommand}" CommandParameter="{Binding }" Foreground="#404040">
                                            <CheckBox.Content>
                                                <StackPanel Orientation="Horizontal">
                                                    <TextBlock Text="{Binding }" Visibility="Visible"  TextWrapping="Wrap" MaxWidth="270"/>
                                                </StackPanel>
                                            </CheckBox.Content>
                                        </CheckBox>
                                    </DataTemplate>
                                </ListBox.ItemTemplate>
                            </ListBox>
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

MainWindow.xaml 代码是

<Window x:Class="SampleControl.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:SampleControl" 
        Title="MainWindow" Height="400" Width="525">
    <Grid>
        <local:BTextBox 
            ItemsSource="{Binding Collection}" 
            ProviderCommand="{Binding AutoBTextCommand}" 
            AutoItemsSource="{Binding SuggCollection}" />
    </Grid>
</Window>

MainWindow.xaml 的 C# 代码背后的代码

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new StringModel();
    }
}

我有两个 ViewModel

ViewModel #1 StringModel

class StringModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private ObservableCollection<string> _collection = new ObservableCollection<string>();
    private ObservableCollection<string> _suggCollection = new ObservableCollection<string>();
    private ObservableCollection<string> _primaryCollection = new ObservableCollection<string>();

    public ObservableCollection<string> Collection
    {
        get { return _collection; }
        set
        {
            _collection = value;
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Collection"));
        }
    }

    public ObservableCollection<string> SuggCollection
    {
        get { return _suggCollection; }
        set
        {
            _suggCollection = value;
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("SuggCollection"));
        }
    }

    public StringModel()
    {
        _primaryCollection = new ObservableCollection<string> { 
            "John", "Jack", "James", "Emma", "Peter"
        };
    }

    public ICommand AutoBTextCommand
    {
        get
        {
            return new DelegatingCommand((obj) =>
            {
                Search(obj as string);
            });
        }
    }

    private void Search(string str)
    {
        SuggCollection = new ObservableCollection<string>(_primaryCollection.Where(m => m.ToLowerInvariant().Contains(str.ToLowerInvariant())).Select(m => m));
    }

}

ViewModel #2 IntModel

class IntModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private ObservableCollection<int> _collection = new ObservableCollection<int>();
    private ObservableCollection<int> _suggCollection = new ObservableCollection<int>();
    private ObservableCollection<int> _primaryCollection = new ObservableCollection<int>();

    public ObservableCollection<int> Collection
    {
        get { return _collection; }
        set
        {
            _collection = value;
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Collection"));
        }
    }

    public ObservableCollection<int> SuggCollection
    {
        get { return _suggCollection; }
        set
        {
            _suggCollection = value;
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("SuggCollection"));
        }
    }

    public IntModel()
    {
        _primaryCollection = new ObservableCollection<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                                                                11, 12, 13, 14, 16, 17, 18, 19, 20 };
    }

    public ICommand AutoBTextCommand
    {
        get
        {
            return new DelegatingCommand((obj) =>
            {
                Search(obj as string);
            });
        }
    }

    private void Search(string str)
    {
        int item = 0;
        int.TryParse(str, out item);
        SuggCollection = new ObservableCollection<int>(_primaryCollection.Where(m => m == item).Select(m => m));
    }

}

【问题讨论】:

  • 简短的回答是ObservableCollection&lt;T&gt; 实现IList&lt;T&gt;,所以只有ObservableCollection&lt;object&gt; 实现IList&lt;object&gt;,但在你的情况下Tstringint。在这两种情况下ItemsSource as IList&lt;object&gt; 产生null。通常,在这种情况下进行的方法是将集合强制转换为非泛型IList 接口(@98​​7654360@ 实现),并具有Add(object) 方法。但是这段代码还有其他几个问题会阻止它工作(特别是OnItemsSourceChanged 方法)。我支持结束投票。

标签: c# wpf xaml mvvm custom-controls


【解决方案1】:

首先,这篇文章更适合 CodeReview。

第二,我可以想象,你想要做什么。 为了缩短内容,我建议您不要在您的情况下使用通用集合。

我稍微修改了控制:

public class BTextBox : ItemsControl {

    static BTextBox() {
      DefaultStyleKeyProperty.OverrideMetadata(typeof(BTextBox), new FrameworkPropertyMetadata(typeof(BTextBox)));
    }

    private TextBox _textBox;
    private ItemsControl _itemsView;

    public static readonly DependencyProperty ProviderCommandProperty = DependencyProperty.Register("ProviderCommand", typeof(ICommand), typeof(BTextBox), new PropertyMetadata(null));
    public static readonly DependencyProperty AutoItemsSourceProperty = DependencyProperty.Register("AutoItemsSource", typeof(IEnumerable), typeof(BTextBox), new PropertyMetadata(null, OnItemsSourceChanged));

    public IEnumerable AutoItemsSource {
      get {
        return (IEnumerable)GetValue(AutoItemsSourceProperty);
      }
      set {
        SetValue(AutoItemsSourceProperty, value);
      }
    }

    private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
      var tb = d as BTextBox;
      if ((e.NewValue != null) && ((tb.ItemsSource as IList) != null)) {
        foreach (var item in e.NewValue as IEnumerable) {
          (tb.AutoItemsSource as IList).Add(item);
        }

      }
    }

    public override void OnApplyTemplate() {
      this._textBox = this.GetTemplateChild("PART_TextBox") as TextBox;
      this._itemsView = this.GetTemplateChild("PART_ListBox_Sugg") as ItemsControl;
      this._itemsView.ItemsSource = this.AutoItemsSource;
      this._textBox.TextChanged += (sender, args) => {
        this.ProviderCommand?.Execute(this._textBox.Text);
      };

      base.OnApplyTemplate();
    }

    public ICommand ProviderCommand {
      get {
        return (ICommand) this.GetValue(ProviderCommandProperty);
      }
      set {
        this.SetValue(ProviderCommandProperty, value);
      }
    }

    public ICommand AddCommand {
      get {
        return new RelayCommand(obj => {
          (this.ItemsSource as IList)?.Add(obj);
        });
      }
    }

  }

然后我已经修复了您的 XAML 以使事情甚至可以编译和运行:

<Style TargetType="{x:Type local:BTextBox}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:BTextBox}">
                    <Border Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}">
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="40"/>
                                <RowDefinition Height="Auto"/>
                            </Grid.RowDefinitions>
                            <TextBox x:Name="PART_TextBox" Grid.Row="0"  VerticalAlignment="Center" />
                            <ListBox ItemsSource="{TemplateBinding AutoItemsSource}" Grid.Row="1" x:Name="PART_ListBox_Sugg" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
                                <ListBox.ItemTemplate>
                                    <DataTemplate>
                                        <CheckBox Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:BTextBox}}, Path=AddCommand}" CommandParameter="{Binding}" Foreground="#404040">
                                            <CheckBox.Content>
                                                <StackPanel Orientation="Horizontal">
                                                    <TextBlock Text="{Binding }" Visibility="Visible"  TextWrapping="Wrap" MaxWidth="270"/>
                                                </StackPanel>
                                            </CheckBox.Content>
                                        </CheckBox>
                                    </DataTemplate>
                                </ListBox.ItemTemplate>
                            </ListBox>
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

最后是有价值的评论:

永远不要在您的 ItemsSources 上允许 setter。如果您覆盖它们,绑定将中断。请改用.Clear().Add(),如下所示:

public class StringModel : INotifyPropertyChanged {
    public event PropertyChangedEventHandler PropertyChanged;

    private readonly ObservableCollection<string> _collection = new ObservableCollection<string>();
    private readonly ObservableCollection<string> _suggCollection = new ObservableCollection<string>();
    private readonly ObservableCollection<string> _primaryCollection = new ObservableCollection<string>();

    public ObservableCollection<string> Collection => this._collection;

    public ObservableCollection<string> SuggCollection => this._suggCollection;

    public StringModel() {
      this._primaryCollection.Add("John");
      this._primaryCollection.Add("Jack");
      this._primaryCollection.Add("James");
      this._primaryCollection.Add("Emma");
      this._primaryCollection.Add("Peter");
    }

    public ICommand AutoBTextCommand {
      get {
        return new RelayCommand(obj => {
          this.Search(obj as string);
        });
      }
    }

    private void Search(string str) {
      this.SuggCollection.Clear();
      foreach (var result in this._primaryCollection.Where(m => m.ToLowerInvariant().Contains(str.ToLowerInvariant())).Select(m => m)) {
        this.SuggCollection.Add(result);
      }

    }

  }

注意

我没有你的DelegateCommand-实现,我用我的RelayCommand 代替。您可以在没有任何问题的情况下更改它。我认为它是相同的东西,但它的名称不同。
您也可以考虑从一开始就显示您的建议。这可能会提供更好的用户体验,但这只是我的意见

【讨论】:

  • 感谢您的回答。请帮助我如何使用 LINQ 在(tb.AutoItemsSource as IList) 中查询?
  • 对不起,我想我不明白你的问题
  • 谢谢,我需要绑定单个项目而不是列表。有没有像 IList 这样的接口?请帮助我...
  • 如果真的想只绑定一个项目,你可以使用object。但是,我认为这没有多大意义。对于单个项目,您不需要 ItemsControl 或其派生词之一
  • 我需要更多帮助来解决这个新问题,stackoverflow.com/questions/39462765/…
猜你喜欢
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2012-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多