MainPage 和 UserControl 之间的通信

Communication between MainPage and UserControl

我正在尝试从 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

的代码隐藏
public sealed partial class uc : UserControl
    {
        public uc()
        {
            this.InitializeComponent();
        }

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

所以我的问题是,我是否有可能从我的 Usercontroll 中获取位于 MainPage 中的 TextBlock

谢谢!

好吧,如果您希望从 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;;
        };
    }
}