簡體   English   中英

將bool倒置為dataContext到userControl的單選按鈕

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM