|ZYCWPF| WPF中的MVVM模式,我会Binding控件相应的属性,但是如何Binding控件的Children呢?谢谢
比如我要给窗体绑定标题,我可又在ViewModel中
private string title; /// <summary> /// 标题 /// </summary> public string Title { get { return title; } set { title = value; this.RaisePropertyChanged("Title"); } }
using System.Windows;using System.Windows.Controls;using System.Windows.Interactivity;using System.Linq;namespace WpfApp1{ public partial class MainWindow { public MainWindow() { InitializeComponent(); } Label _label = new Label {Content = "dynamic label"}; TextBox _text = new TextBox {Text = "dynamic text", Margin = new Thickness(150, 0, 0, 0 ) }; public UIElementCollection CanvasChildren { get { return new UIElementCollection(this, null) { _label, _text }; } } } public class BindChildren : Behavior<Panel> { private static readonly DependencyProperty ChildrenProperty = DependencyProperty.Register("Children", typeof (UIElementCollection), typeof (BindChildren)); public UIElementCollection Children { get { return (UIElementCollection)GetValue(ChildrenProperty); } set { SetValue(ChildrenProperty, value); } } protected override void OnAttached() { if (Children != null) { var children = Children.Cast<UIElement>().ToList(); Children.Clear(); // remove all children from original container in order to add it to new container children.ForEach(child => this.AssociatedObject.Children.Add(child)); } } }}