WP8 silverlight:无法在DataTemplate中找到文本块

时间:2014-08-24 13:39:19

标签: c# xaml windows-phone-8 windows-phone silverlight-toolkit

我知道这个问题必须已经提出,但我找不到任何有用的答案。

我有一个工具包的CustomMessageBox,非常类似于这个Microsoft示例:

CustomMessageBox messageBox = new CustomMessageBox()
        {
            ContentTemplate = (DataTemplate)this.Resources["myContentTemplate"],
            LeftButtonContent = "speak",
            RightButtonContent = "read it",
            IsFullScreen = false 
        };

        messageBox.Dismissed += (s1, e1) =>
        {
            switch (e1.Result)
            {
                case CustomMessageBoxResult.LeftButton:
                    // Do something.
                    break;
                case CustomMessageBoxResult.RightButton:
                    // Do something.
                    break;
                case CustomMessageBoxResult.None:
                    // Do something.
                    break;
                default:
                    break;
            }
        };

        messageBox.Show();

消息框内容在DataTemplate中定义,以简化:

<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="myContentTemplate">
        <TextBlock x:Name="myTextBlock" />
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>

如何通过代码隐藏设置myTextBlock.Text

它说命名空间中不存在myTextBlock

它在WinRT应用程序中有效,但在Silverlight中无效...

1 个答案:

答案 0 :(得分:3)

我建议您使用TextBlock.Text代替Databind。但如果你真的想要遍历那个对象。您需要从该组件派生自定义消息框,并且在OnApplyTemplate上,您可以使用GetTemplateChild()轻松地让孩子们。

但是如果你想要这么做的话:你可以使用VisualTreeHelper,事实上有人已经给你写了一个很好的遍历函数: FindVisualChildByName


解决您的绑定问题

示例绑定类

public class MainViewModel : INotifyPropertyChanged
{
    private string _messagebox_text = "";
    public string messagebox_text
    {
        get
        {
            return _messagebox_text;
        }
        set
        {
            _messagebox_text = value;
            NotifyPropertyChanged("messagebox_text");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (null != handler)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

然后您的DataTemplate将更改为:

<phone:PhoneApplicationPage.Resources>
    <DataTemplate x:Key="myContentTemplate">
        <TextBlock x:Name="myTextBlock" Text="{Binding messagebox_text}" />
    </DataTemplate>
</phone:PhoneApplicationPage.Resources>

然后您需要正确设置DataContext。诀窍是当你处理DataTemplate时,DataContext实际设置在内容

所以把它们放在一起

MainViewModel _mvm = new MainViewModel();
_mvm.messagebox_text = "what ever";

messageBox = new CustomMessageBox()
{
    ContentTemplate = (DataTemplate)this.Resources["myContentTemplate"],                
    LeftButtonContent = "speak",
    RightButtonContent = "read it",
    IsFullScreen = false

};

messageBox.Content = _mvm;  // set the bind