WPF绑定用户控件与C#代码中的数据

时间:2009-09-25 13:41:39

标签: wpf user-controls binding

我已经创建了这样的用户控件:

public partial class View
    {
        public View()
        {
            InitializeComponent();
        }

        public static DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(TeaserView) );

        public string Name
        {
            get { return (string)GetValue(NameProperty); }
            set { SetValue(NameProperty, value); }
        }

    }

XAML:

<UserControl x:Class="Controls.View"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="200" Width="164">
    <Grid VerticalAlignment="Stretch"
          x:Name="Preview">

        <Label Height="28"  Content="{Binding ElementName=Preview, Path=Name}" Background="LightYellow" x:Name="name" VerticalAlignment="Top" ></Label>
    </Grid>
</UserControl>

并在XAML中仅在Window1中使用它:

<controls:View Height="200" Name="View1" Width="164" />

我尝试在C#中设置内容(此示例中为Name属性)但它确实无效,标签的内容仍为空。 (所有的参考等都很好)出了什么问题?

5 个答案:

答案 0 :(得分:3)

你的代码错了。绑定到Grid.Name属性,即“预览”,而不是View.Name。

我真的很鼓励你在MSDN上阅读A到Z“DataBinding Overview”。值得你花时间,相信我:)。事实上,整个“Windows Presentation Foundation”部分值得您关注。

至于您的代码,以下内容将起作用:

<UserControl x:Class="WpfApplication5.View"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Height="300"
             Width="300"
             DataContext="{Binding RelativeSource={RelativeSource Self}}">
  <Grid>
    <Label Height="28"
           Content="{Binding Path=Name}"
           Background="LightYellow"
           VerticalAlignment="Top"/>
  </Grid>
</UserControl>

但你确定要隐藏父母的“姓名”属性吗?

答案 1 :(得分:1)

您是否在用户控件上设置了datacontext?尝试将其设置为指向自己的代码隐藏:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

答案 2 :(得分:0)

复制了您的确切代码,效果很好。

然而,它并没有做你可能期望它做的事情。您正在将绑定源设置为Grid实例。因此,Name属性将产生“预览”。您在UserControl中定义的名称属性将被忽略,因为Name上已存在UserControl属性。

答案 3 :(得分:0)

我把Name属性作为样本。我正在尝试在Window1.xaml.cs中设置标签内容,如:

View1.Name = "Casablanca";

答案 4 :(得分:0)

尝试以下绑定,它应该有效:

<Label Content="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:View}}, Path=Name}" />

您还应该在文件顶部定义xmlns:local =“whatever_path_you_have”。

我还建议将“名称”DP重命名为其他名称以避免名称勾结。