Search code examples
c#.netwpfxamldatacontext

How to get datacontext from stackpanel


I have:

<StackPanel  DataContext="{Binding Path =MyContext}">
    <TextBox Text="{Binding Path =Content}" x:Name="tbName" IsReadOnly="False">
    </TextBox>
    <CheckBox x:Name="cboxName" Content="Is null ?" Click="cboxName_Click" IsChecked="{Binding Path=THIS, Converter={StaticResource MyContextToBoolConverter}}">
     </CheckBox>
</StackPanel>

public class MyContextToBoolConverter: IValueConverter
{
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
     {
         return (value!=null);
     }

     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
     {
            return parameter;
     }
}

I just only want to get DataContext to checkbox from StackPanel.


Solution

  • Or try this -

    <StackPanel x:Name="StackPanel" DataContext="{Binding Path =MyContext}"> 
       <TextBox Text="{Binding Path =Content}" x:Name="tbName" IsReadOnly="False" /> 
       <CheckBox x:Name="cboxName" Content="Is null ?" 
           Click="cboxName_Click" 
           IsChecked="{Binding ElementName=StackPanel, Path=DataContext, Converter={StaticResource MyContextToBoolConverter}}"> 
       </CheckBox> 
    </StackPanel>