Jos*_*ant 18 data-binding wpf user-controls
在开发WPF UserControls时,将子控件的DependencyProperty公开为UserControl的DependencyProperty的最佳方法是什么?以下示例显示了我当前如何在UserControl中公开TextBox的Text属性.当然有更好/更简单的方法来实现这一目标?
<UserControl x:Class="WpfApplication3.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel Background="LightCyan">
<TextBox Margin="8" Text="{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" />
</StackPanel>
</UserControl>
using System;
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication3
{
public partial class UserControl1 : UserControl
{
public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new PropertyMetadata(null));
public string Text
{
get { return GetValue(TextProperty) as string; }
set { SetValue(TextProperty, value); }
}
public UserControl1() { InitializeComponent(); }
}
}
Run Code Online (Sandbox Code Playgroud)
use*_*116 17
这就是我们在没有RelativeSource搜索的情况下在团队中执行此操作的方式,而是通过UserControl的名称命名UserControl和引用属性.
<UserControl x:Class="WpfApplication3.UserControl1" x:Name="UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel Background="LightCyan">
<TextBox Margin="8" Text="{Binding Path=Text, ElementName=UserControl1}" />
</StackPanel>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
有时我们发现自己制造了太多的UserControl,但往往会缩减我们的使用量.我也遵循沿着PART_TextDisplay或类似的方式命名像文本框这样的东西的传统,以便将来你可以将其模板化,但保持代码隐藏相同.
| 归档时间: |
|
| 查看次数: |
8196 次 |
| 最近记录: |