设置控件DataContext并将其他属性绑定到父上下文

时间:2018-08-29 01:43:05

标签: xaml uwp

我具有以下类结构设置。

public class Control1
{
   public Control1()
    {
       Control2Model = new Control2();
    }

   public Control2 Control2Model {get; set;}
   public bool IsControlTwoVisible => true;

}

在我的xaml中,我有一个名为CustomUserControl的UserControl,我想将Control2Model传递给它。我还想将IsControlTwoVisible绑定到我的CustomUserControls Visibility属性。

<UserControl x:Class="Control1">
  <StackPanel>

     <!--Other controls above this-->

    <CustomUserControl
        DataContext="{Binding Control2Model }"
        Visibility="{Binding IsControlTwoVisible, Converter={StaticResource VisibilityConverter}" />

  </StackPanel>
 </UserControl>

但是我收到绑定错误,因为CustomUserControlIsControlTwoVisible上找不到Control2Model

在仍然可以访问CustomUserControls的属性的同时,我可以设置Control1上下文吗?

请注意,我想避免将IsControlTwoVisible移至Control2

1 个答案:

答案 0 :(得分:1)

我建议不要在DataContext中设置Control1,而应该在CustomUserControl内部的顶部网格中设置。这样可以解决您的问题。

请参考以下代码以供参考:

Control1.xaml

<UserControl x:Class="Control1">
  <StackPanel>

     <!--Other controls above this-->

    <CustomUserControl
        Visibility="{Binding IsControlTwoVisible, Converter={StaticResource VisibilityConverter}" />

  </StackPanel>
 </UserControl>

CustomUserControl.xaml

<UserControl
    x:Class="UWPBlankApp.CustomUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UWPBlankApp"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="400">

    <Grid  DataContext="{Binding Control2Model}">
       <!--Other controls-->
    </Grid>
</UserControl>