[英]Inverted bool to radio button from dataContext to userControl
如何在xaml中绑定布尔值的倒数?
我知道,我对此有很多疑问,但是并没有关于特定情况的信息:转换器处于视图模型中,而单选按钮位于用户控件中。
如何正确引用主窗口视图模型数据上下文? 在其他情况下,我使用了已发布的代码,但是在这种情况下,我不知道如何使用它。
更新代码:
namespace ***.ViewModel
{
[ValueConversion(typeof(bool), typeof(bool))]
public class InverseBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (targetType != typeof(bool))
throw new InvalidOperationException("The target must be a boolean");
return !(bool)value;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
class MainWindowViewModel : MyClass.UtilityClasses.ViewModelBase
{
public MainWindowViewModel(){
SaveCommand = new DelegateCommand(SaveData, CanSave );
UndoCommand = new DelegateCommand(UndoActions, CanSave);
[...]
}
....
}
另一个代码更新:
在我的xaml中,我有一个devexpress GridControl,在其中列出了来自db的observableCollection。 当我单击一个元素时,布局组将填充相关数据。
在此布局组中,我具有:
<StackPanel Margin="0" Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Left">
<RadioButton Content="{DynamicResource Locale}" Margin="10,0,0,0" x:Name="rd_LOCALE" VerticalAlignment="Center" IsChecked="{Binding Path=REMOTO, Converter={StaticResource InverseBooleanConverter}}" GroupName="Location" Panel.ZIndex="9" TabIndex="10" />
<RadioButton Content="{DynamicResource Remoto}" Margin="10,0,6,0" x:Name="rd_REMOTO" VerticalAlignment="Center" IsChecked="{Binding REMOTO}" GroupName="Location" Panel.ZIndex="10" TabIndex="11" Tag="PRISMA" />
</StackPanel>
当我从一条记录更改为另一条记录时,转换器给我错误...为什么? 它在“ if(targetType!= typeof(bool))”行中失败。 因此,我尝试将其更改为:
if (value.getType() != typeof(bool))
但是通过这种方式,在代码中没有失败的情况下,它在单选按钮中输入了错误的值!
您需要确保XAML中引用了值转换器
<UserControl.Resources>
<myproject:InverseBooleanConverter x:Key="InverseBooleanConverter" />
</UserControl.Resources>
我的项目是在其中定义值转换器类的名称空间
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.