CheckBox 绑定到 WP8.1 中的元素问题
CheckBox binding to element issue in WP8.1
我有一个简单的XAML:
<CheckBox x:Name="chkShowGrid" IsThreeState="False" IsChecked="False">Show content</CheckBox>
<Grid Visibility="{Binding IsChecked, ElementName=chkShowGrid}">
<TextBlock>Some content goes here</TextBlock>
</Grid>
此 XAML 在 WinRT Windows 8.1 应用程序中运行良好。当我在 WP8.1 应用程序中尝试它时,它在设计器中工作(显示或隐藏网格取决于复选框值),但不在 phone 上。为什么?
更新:
我有通用的 8.1 应用程序,如果使用转换器然后显示异常:
error CS0012: The type 'Type' is defined in an assembly that is not
referenced. You must add a reference to assembly 'System.Runtime,
Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
转换器代码:
class BoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null) return false;
return (bool)value;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
在XAML
<Page.Resources>
<local:BoolConverter x:Name="ThatsMyConverter"/>
</Page.Resources>
.......
<Grid Visibility="{Binding IsChecked, ElementName=chkShowSettings,Converter={StaticResource ThatsMyConverter}}">
您的转换器 returns 一个布尔值,您正在尝试将布尔值分配给 Visibility,它只能将 Visible 或 Collapsed 作为可能的值。尝试从您的转换器而不是 bool 返回可见性。那应该有效。例如在您的转换器中:
if (value == null) return Visibility.Collapses;
var val = (value as bool);
if (val)
return Visibility.Visible;
else
return Visibility.Collapsed;
我有一个简单的XAML:
<CheckBox x:Name="chkShowGrid" IsThreeState="False" IsChecked="False">Show content</CheckBox>
<Grid Visibility="{Binding IsChecked, ElementName=chkShowGrid}">
<TextBlock>Some content goes here</TextBlock>
</Grid>
此 XAML 在 WinRT Windows 8.1 应用程序中运行良好。当我在 WP8.1 应用程序中尝试它时,它在设计器中工作(显示或隐藏网格取决于复选框值),但不在 phone 上。为什么?
更新: 我有通用的 8.1 应用程序,如果使用转换器然后显示异常:
error CS0012: The type 'Type' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
转换器代码:
class BoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null) return false;
return (bool)value;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
在XAML
<Page.Resources>
<local:BoolConverter x:Name="ThatsMyConverter"/>
</Page.Resources>
.......
<Grid Visibility="{Binding IsChecked, ElementName=chkShowSettings,Converter={StaticResource ThatsMyConverter}}">
您的转换器 returns 一个布尔值,您正在尝试将布尔值分配给 Visibility,它只能将 Visible 或 Collapsed 作为可能的值。尝试从您的转换器而不是 bool 返回可见性。那应该有效。例如在您的转换器中:
if (value == null) return Visibility.Collapses;
var val = (value as bool);
if (val)
return Visibility.Visible;
else
return Visibility.Collapsed;