Silverlight UserControl自定义属性绑定

时间:2009-10-06 16:46:27

标签: silverlight binding user-controls

在Silverlight UserControls中实现自定义属性的正确方法是什么?

Silverlight中的每个“Page”在技术上都是UserControl(它们派生自UserControl类)。当我在这里说UserControl时,我指的是一个自定义UserControl,它将在许多不同场景中的许多不同页面中使用(类似于ASP.NET UserControl)。

我希望Custom UserControl支持Binding,而不依赖于它绑定的Property的名称,始终保持相同。相反,我希望UserControl本身具有UserControl中的Controls绑定到的属性,UserControl外部的ViewModels也绑定到该属性。 (请参阅下面的例子)

UserControl中的绑定工作,MainPage中的绑定工作,我在MainPage和UserControl之间设置的绑定不起作用。特别是这一行:

<myUserControls:MyCustomUserControl x:Name="MyCustomControl2" 
    SelectedText="{Binding MainPageSelectedText, Mode=TwoWay}" 
    Width="200" Height="50" />

示例输出:
alt text

MainPage.xaml中

<UserControl x:Class="SilverlightCustomUserControl.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:myUserControls="clr-namespace:SilverlightCustomUserControl"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
  <Canvas x:Name="LayoutRoot">
    <StackPanel Orientation="Vertical">
      <TextBlock Text="UserControl Binding:" Width="200"></TextBlock>
      <myUserControls:MyCustomUserControl x:Name="MyCustomControl2" SelectedText="{Binding MainPageSelectedText, Mode=TwoWay}" Width="200" Height="50" />
      <TextBlock Text="MainPage Binding:" Width="200"></TextBlock>
      <TextBox Text="{Binding MainPageSelectedText, Mode=TwoWay}" Width="200"></TextBox>
      <Border BorderBrush="Black" BorderThickness="1">
        <TextBlock Text="{Binding MainPageSelectedText}" Width="200" Height="24"></TextBlock>
      </Border>
    </StackPanel>
  </Canvas>
</UserControl>

MainPage.xaml.cs中

namespace SilverlightCustomUserControl
{
 public partial class MainPage : UserControl, INotifyPropertyChanged
 {
  //NOTE: would probably be in a ViewModel
  public string MainPageSelectedText
  {
   get { return _MainPageSelectedText; }
   set
   {
    string myValue = value ?? String.Empty;
    if (_MainPageSelectedText != myValue)
    {
     _MainPageSelectedText = value;
     OnPropertyChanged("MainPageSelectedText");
    }
   }
  }
  private string _MainPageSelectedText;


  public MainPage()
  {
   InitializeComponent();
  }


  #region INotifyPropertyChanged Members

  public event PropertyChangedEventHandler PropertyChanged;

  protected virtual void OnPropertyChanged(string name)
  {
   PropertyChangedEventHandler ph = this.PropertyChanged;

   if (ph != null)
    ph(this, new PropertyChangedEventArgs(name));
  }

  #endregion
 }
}

MyCustomUserControl.xaml

<UserControl
   x:Class="SilverlightCustomUserControl.MyCustomUserControl" 
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   DataContext="{Binding RelativeSource={RelativeSource Self}}">
  <Grid>
    <StackPanel>
      <TextBox Text="{Binding SelectedText, Mode=TwoWay}" />
      <Border BorderBrush="Black" BorderThickness="1">
        <TextBlock Text="{Binding SelectedText}" Height="24"></TextBlock>
      </Border>
    </StackPanel>
  </Grid>
</UserControl>

MyCustomUserControl.xaml.cs

namespace SilverlightCustomUserControl
{
 public partial class MyCustomUserControl : UserControl
 {
  public string SelectedText
  {
   get { return (string)GetValue(SelectedTextProperty); }
   set { SetValue(SelectedTextProperty, value); }
  }

  public static readonly DependencyProperty SelectedTextProperty =
    DependencyProperty.Register("SelectedText", typeof(string), typeof(MyCustomUserControl), new PropertyMetadata("", SelectedText_PropertyChangedCallback));


  public MyCustomUserControl()
  {
   InitializeComponent();
  }

  private static void SelectedText_PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
   //empty
  }
 }
}

参考文献(我是如何做到这一点的):

使用DependencyPropertys: http://geekswithblogs.net/thibbard/archive/2008/04/22/wpf-custom-control-dependency-property-gotcha.aspx

使用DependencyPropertys,将x:Name添加到UserControl - 使用ElementName添加Binding,再次在PropertyChangedCallback方法中设置Custom属性: Setting Custom Properties in UserControl via DataBinding

不要使用自定义属性,依赖底层的datacontext名称(我不喜欢这个解决方案): wpf trouble using dependency properties in a UserControl

3 个答案:

答案 0 :(得分:7)

我理解它是你的控件没有从maim页面接收新值的原因是你正在设置控件的DataContext。如果还没有,那么控件的DataContext将从其父级继承,在这种情况下是主页面。

为了实现这一点,我删除了你的控件的DataContext设置,为每个控件添加了一个x:Name,并使用[name] .SetBinding方法在控件的构造函数中设置绑定。

我在ctor中进行了绑定,因为我无法找到将xaml中的声明性绑定的Source属性设置为Self的方法。即{Binding SelectedText,Mode = TwoWay,Source = [Self here some how] 2}。我确实尝试过使用RelativeSource = {RelativeSource Self}而没有任何快乐。

注意:所有这些都是SL3。

答案 1 :(得分:4)

问题是UserControl抛出了一个DataBinding错误(在调试时在Output窗口中可见)

因为UserControl的DataContext在其自己的xaml中被设置为“Self”,所以它在自己的上下文中寻找MainPageSelectedText(它没有在“MainPage”中寻找MainPageSelectedText,这可能是你认为它看起来的地方,因为当你在实际编写/查看“上下文”中的代码时)

通过在后面的代码中设置Binding,我能够“正常工作”。在后面的代码中设置绑定是将UserControl本身设置为绑定的“源”的唯一方法。但这仅在绑定为TwoWay时才有效。 OneWay绑定将破坏此代码。一个更好的解决方案是创建Silverlight Control ,而不是 UserControl

另见:

http://social.msdn.microsoft.com/Forums/en-US/silverlightcontrols/thread/052a2b67-20fc-4f6a-84db-07c85ceb3303

http://msdn.microsoft.com/en-us/library/cc278064%28VS.95%29.aspx

MyCustomUserControl.xaml

<UserControl
   x:Class="SilverlightCustomUserControl.MyCustomUserControl" 
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
 <Grid>
  <StackPanel>
   <TextBox x:Name="UserControlTextBox" />
   <Border BorderBrush="Black" BorderThickness="1">
    <TextBlock x:Name="UserControlTextBlock" Height="24"></TextBlock>
   </Border>
  </StackPanel>
 </Grid>
</UserControl>

MyCustomUserControl.xaml.cs

namespace SilverlightCustomUserControl
{
 public partial class MyCustomUserControl : UserControl
 {

  public string SelectedText
  {
   get { return (string)GetValue(SelectedTextProperty); }
   set { SetValue(SelectedTextProperty, value); }
  }

  public static readonly DependencyProperty SelectedTextProperty =
    DependencyProperty.Register("SelectedText", typeof(string), typeof(MyCustomUserControl), new PropertyMetadata("", SelectedText_PropertyChangedCallback));


  public MyCustomUserControl()
  {
   InitializeComponent();

               //SEE HERE
   UserControlTextBox.SetBinding(TextBox.TextProperty, new Binding() { Source = this, Path = new PropertyPath("SelectedText"), Mode = BindingMode.TwoWay });
   UserControlTextBlock.SetBinding(TextBlock.TextProperty, new Binding() { Source = this, Path = new PropertyPath("SelectedText") });
               //SEE HERE
  }

  private static void SelectedText_PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
   //empty
  }

 }
}

答案 2 :(得分:0)

您可以通过为用户控件添加x:Name来设置xaml中的绑定,而不是将数据上下文绑定到self,然后在用户控件xaml中进行绑定:

<UserControl
  x:Class="SilverlightCustomUserControl.MyCustomUserControl" 
  x:Name="myUserControl
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
    <Grid>
        <StackPanel>
            <TextBox Text="{Binding SelectedText, ElementName=myUserContol, Mode=TwoWay}" />
            <Border BorderBrush="Black" BorderThickness="1">
                <TextBlock Text="{Binding SelectedText,ElementName=myUserControl}" Height="24"></TextBlock>
            </Border>
        </StackPanel>
     </Grid>
</UserControl>