|ZYCWPF| WPF中的MVVM模式,我会Binding控件相应的属性,但是如何Binding控件的Children呢?谢谢
比如我要给窗体绑定标题,我可又在ViewModel中
- C# code
private string title; /// <summary> /// 标题 /// </summary> public string Title { get { return title; } set { title = value; this.RaisePropertyChanged("Title"); } }
然后
Title="{Binding Title}"
来进行绑定
但是现在我要对XAML中的一个Canvas来动态添加他的控件
但是我发现在XAML中并没有<Canvas Children 属性可又给我绑定
我在后台定义了:public System.Windows.Controls.UIElementCollection CanvasChildren
那要怎么绑定给这个Canvas啊
谢谢
[解决办法]
具体需求放上来看看
如果说需要列表类型的话可以用itemscontrol控件做绑定
canvas 除非你自己写依赖属性 不然没法绑定内容
[解决办法]
先说下实现方法:
Canvas.Children本身是不能绑定的,我不知道有什么办法能实现绑定。
用behavior是可以的,方法还是绕个圈子在attach的时候把一组control加到cavas中。
看下面的例子:
- C# code
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)); } } }}