繁体   English   中英

DataTemplate中的访问元素

[英]Access Elements in DataTemplate

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

<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

我试过谷歌搜索,但访问DataTemplate项目的解决方案他们都需要VisualTreeHelper.GetChildrenCount通过FindVisualChild ,它为我返回0,所以它不起作用。

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

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

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

在你的myClass实现INotifyPropertyChanged 然后每当你想改变文本调用PropertyChanged事件。

public name
{
    get
    {
        return _name;
    }
    set
    {
        _name = value;
        PropertyChanged("name");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM