DataTemplate中的访问元素

时间:2013-07-25 09:41:30

标签: c# wpf xaml

我有以下项目模板(我试图剥离所有不相关的东西):

<s:SurfaceWindow.Resources>
    <ResourceDictionary>
        <Style TargetType="{x:Type s:SurfaceListBox}">
            <Setter Property="ItemTemplate">
                <DataTemplate DataType="{x:Type local:myClass}"> //my own class
                    <s:SurfaceButton>
                        <TextBlock Text="{Binding name}">        //name is a string in my own class
//and close all the tags

我的想法是我的列表框将包含显示一些单词的按钮。

再往下,我有SurfaceListBox使用上述资源。我通过以下方式添加项目:

myListBox.Items.Add(new myClass("My Name"));

它会很好地为列表框添加一个按钮,按钮显示“我的名字”。

现在我需要将“我的名字”改为另一个字符串。

如何访问TextBlock

我尝试使用Google搜索,但访问DataTemplate中的项目的解决方案都需要VisualTreeHelper.GetChildrenCount通过FindVisualChild,我会返回0,因此无效。

1 个答案:

答案 0 :(得分:2)

实现此目的的简单方法是使用DataBinding

更新TextBlock XAML,以便TextBlock可以在后端name属性更改时自行更新

<TextBlock Text="{Binding name, UpdateSourceTrigger=PropertyChanged}">

在你身上myClass实施INotifyPropertyChanged。然后,只要您想更改文本调用PropertyChanged事件。

public name
{
    get
    {
        return _name;
    }
    set
    {
        _name = value;
        PropertyChanged("name");
    }
}
相关问题