如何从stackpanel获取datacontext

时间:2010-07-05 09:35:16

标签: c# .net wpf xaml datacontext

我有:

<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;
     }
}

我只想从StackPanel获取DataContext复选框。

2 个答案:

答案 0 :(得分:5)

您应该将THIS替换为.或从Path中完全删除Binding。这将直接创建绑定到DataContext

IsChecked="{Binding Converter={StaticResource MyContextToBoolConverter}}"

答案 1 :(得分:1)

或试试这个 -

<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>