WPF中的自定义用户控件,带有数据绑定

时间:2014-10-15 18:06:51

标签: wpf binding user-controls

我想要一个带有一个属性/属性的自定义WPF用户控件,该用户控件的实现者必须能够将它们的值绑定到它。

请参阅此示例:http://www.codeproject.com/Articles/42203/How-to-Implement-a-DependencyProperty

而不是<local:MyUserControl Caption="My First Dependency Property Example" />我需要类似<local:MyUserControl Caption="{Binding MyCaption}" />的内容,其中MyCaption是DataContext viewmodel类中的字符串属性。但是,每当我更改MyCaption值时,它都不会反映在用户控件...

我有自己的代码,我测试相同的原则,但文本永远不会更新:

MainWindow.xaml.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private string _MyFirstName;
        public string MyFirstName
        {
            get
            {
                return _MyFirstName;
            }
            set
            {
                _MyFirstName = value;
                RaisePropertyChanged("MyFirstName");
            }
        }

        public MainWindow()
        {
            InitializeComponent();
        }

        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //this.Klaas.SetValue(NameControl.FirstNameProperty, "Mike");
            MyFirstName = "Mike";
        }
    }
}

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:me="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <me:NameControl x:Name="Klaas" FirstName="{Binding MyFirstName}" Grid.Row="0"/>
        <Button Grid.Row="1" Click="Button_Click">Pick a name</Button>
    </Grid>
</Window>

NameControl.xaml.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for NameControl.xaml
    /// </summary>
    public partial class NameControl : UserControl
    {
        public static readonly DependencyProperty FirstNameProperty = DependencyProperty.Register(
            "FirstName", 
            typeof(string),
            typeof(NameControl),
            new PropertyMetadata("NoName", OnFirstNamePropertyChanged));

        public string FirstName
        {
            get
            {
                return (string)GetValue(FirstNameProperty);
            }
            set
            {
                SetValue(FirstNameProperty, value);
            }
        }

        private static void OnFirstNamePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            NameControl source = d as NameControl;
            // Do something...
        }

        public NameControl()
        {
            InitializeComponent();
        }
    }
}

NameControl.xaml

<UserControl x:Class="WpfApplication1.NameControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300"
         DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <TextBlock Grid.Column="0" Width="100" Text="{Binding FirstName}" />
    <TextBlock Grid.Column="1" Width="100" Text="{Binding LastName}" />
</Grid>
</UserControl>

2 个答案:

答案 0 :(得分:2)

当你这样做时

<UserControl ... DataContext="{Binding RelativeSource={RelativeSource Self}}">

您有效地覆盖通常从可视树传递给您的控件的DataContext,并更改NameControl控件内绑定的绑定上下文。我建议删除它并按照绑定执行此操作

<TextBlock ... Text="{Binding FirstName, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
<TextBlock ... Text="{Binding LastName, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />

或者更简单地为UserControl提供一些名称并将其用于控件内的绑定

<UserControl... x:Name="myUserControl">
   <Grid>
      <Grid.ColumnDefinitions>
         <ColumnDefinition Width="Auto"/>
         <ColumnDefinition Width="Auto"/>
      </Grid.ColumnDefinitions>
      <TextBlock Grid.Column="0" Width="100" Text="{Binding FirstName, ElementName=myUserControl}" />
      <TextBlock Grid.Column="1" Width="100" Text="{Binding LastName, ElementName=myUserControl}" />
   </Grid>
</UserControl>

答案 1 :(得分:0)

好的,所以我将xaml代码更改为:     

为什么所有这些复杂的RelativeSource FindAncestor东西都需要???这是一个非直观的地狱!