绑定到UserControl的问题

时间:2013-10-01 10:25:07

标签: c# wpf user-controls

我有使用usercontrols生成gridview的代码:

 <ListView x:Name="ListView" SelectionMode="None">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid>
                            <UserControls:ItemTemplateControl Parametr="XXXXXXX"/>
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

Listview工作正常,但我无法向UserControl发送任何内容。 UserControl代码:

public sealed partial class ItemTemplateControl : UserControl
    {
        public string Parametr
        {
            get
            {
                return (string)GetValue(ParametrProperty);
            }
            set
            {
                SetValue(ParametrProperty, value);
            }
        }
        public static DependencyProperty ParametrProperty = DependencyProperty.Register("Parametr", typeof(string), typeof(ItemTemplateControl), new PropertyMetadata(""));


        public ItemTemplateControl()
        {
            this.InitializeComponent();
            post_text.Text = Parametr;
            Get();
        }

此代码无效!我现在不在哪里?

抱歉我的英文

<Page
    x:Class="App13.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App13"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:UserControls="using:App13.UserControls"
    mc:Ignorable="d">

1 个答案:

答案 0 :(得分:1)

我想你想要在依赖属性Parametr发生变化时注册回调。要做到这一点,你必须:

public static DependencyProperty ParametrProperty = DependencyProperty.Register("Parametr", typeof(string), typeof(ItemTemplateControl), new PropertyMetadata("", ParametrChanged));

并在ParametrChanged方法

中定义一些逻辑
private static void ParametrChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
       var sender = d as ItemTemplateControl;
       if (sender == null) return;

       var newValue = e.NewValue as string;
       sender.post_text.Text = newValue;
}