110,536
社区成员
发帖
与我相关
我的任务
分享
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));
}
}
}
}
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
>
<Canvas>
<i:Interaction.Behaviors>
<local:BindChildren Children="{Binding CanvasChildren}" />
</i:Interaction.Behaviors>
</Canvas>
</Window>
<Canvas Name="loginCanvas" Grid.Column="1" Canvas.Children="{Binding canvasChildren}" Grid.Row="1" Width="500" Height="300" VerticalAlignment="Top" HorizontalAlignment="Center" >
</Canvas>
public MainWindow()
{
InitializeComponent();
loginCtrl = new LoginControl(this);
this.loginCanvas.Children.Add(loginCtrl);
}