MainPage和UserControl之间的通信

时间:2015-01-24 11:01:19

标签: xaml

我试图从Usercontroll对我的MainPage进行更改。如果我们采取以下方案:

MainPage包含UC和文本块:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">        

    <local:uc></local:uc>
    <TextBlock Text="Hide me from the UC!" />

 </Grid>

UserControll仅包含一个按钮:

<Button Content="Button" Click="Button_Click" />

以下是UserControll

的CodeBehind
public sealed partial class uc : UserControl
    {
        public uc()
        {
            this.InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //Do stuff to element in MainPage
        }
    }

所以我的问题是,我是否有可能从我的TextBlock获取位于MainPage内的Usercontroll个数字?

谢谢!

1 个答案:

答案 0 :(得分:1)

好吧,如果您要在UserControl中操作的页面中的元素始终为TextBlock,则可以将对它的引用传递给UserControl。为此,您需要在UserControl中创建类型为TextBlock的依赖项属性,并将引用存储在私有字段中,以便您可以从按钮的事件处理程序中访问它:

private TextBlock _myText;

public static readonly DependencyProperty MyTextProperty = DependencyProperty.Register(
    "MyText", typeof (TextBlock), typeof (uc), new PropertyMetadata(default(TextBlock), PropertyChangedCallback));

public TextBlock MyText
{
    get { return (TextBlock) GetValue(MyTextProperty); }
    set { SetValue(MyTextProperty, value); }
}

private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
{
    var self = dependencyObject as uc;
    var element = args.NewValue as TextBlock;
    if (self != null && element != null)
        self._myText = element;
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (_myText != null)
        _myText.Visibility = Visibility.Collapsed;
}

在这种情况下,您将TextBlock绑定到UserControl,如:

<TextBlock x:Name="SomeTextBlock"/>
<local:uc MyText="{Binding ElementName=SomeTextBlock}"/>

当然,您也可以使用类型UIElement的依赖项属性来更灵活。

或者,在单击按钮时触发UserControl中的事件,并让页面本身决定在这种情况下要做什么(例如,隐藏一些TextBlock):

public partial class uc : UserControl
{
    public event EventHandler OnButtonClicked;
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (OnButtonClicked != null)
            OnButtonClicked(this, new EventArgs());
    }
}

public partial class MainPage : Page
{
    public MainPage()
    {
        uc.OnButtonClicked += (sender, args) =>
        {
            SomeTextBlock.Visibility = Visibility.Collapsed;;
        };
    }
}