在C#code数据绑定WPF用户控件 [英] WPF binding user control with data in C# code

查看:133
本文介绍了在C#code数据绑定WPF用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've create user control like this:

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中使用它在窗口1:

and use it in Window1 simply in XAML:

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

和我尝试设置(此示例中的Name属性)在C#中的内容,但does'n工作,标签的内容仍然是空的。 (所有refereces等都是不错的)怎么了?

and I try set the Content in C# (Name property in this sample) but it does'n work, label's content is still empty. (All refereces, etc. are good) What's wrong?

推荐答案

您code是错误的。您绑定到Grid.Name属性,它是preVIEW,而不是View.Name。

Your code is wrong. You bind to Grid.Name property, which is "Preview", not to View.Name.

我真的鼓励你去从A读到Z数据绑定概述MSDN上。它值得你花时间,相信我:)。其实整个的Windows presentation基金会部分将是值得的您的关注。

I really encourage you to go read from A to Z "DataBinding Overview" on MSDN. It worth your time, trust me :). In fact whole "Windows Presentation Foundation" section would be worth your attention.

至于你的code,下面的工作:

As for your code, the following will work:

<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>

但你确定要隐藏的父母名称属性?

But are you sure you want to hide "Name" property from parents?

这篇关于在C#code数据绑定WPF用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆