【问题标题】:Accessing another datacontext inside a ListView with a ItemSource-binding使用 ItemSsource 绑定访问 ListView 中的另一个数据上下文
【发布时间】:2024-01-11 01:49:01
【问题描述】:

我正在使用 XAML 开发一个 MVVM 项目。 在带有 ItemSource 绑定的 ListView 中操作时,我在访问外部元素的属性时遇到问题。

XAML:

<ListView x:Name="BibTexFields" Height="422" ItemsSource="{Binding BibTexFields}">
    <ListView.ItemTemplate>
        <DataTemplate>
           <Grid Width="450">
              <TextBlock Foreground="Black" Text="{Binding Field.Name}"/>
              <CheckBox HorizontalAlignment="Right" IsChecked="{Binding IsChecked, Mode=TwoWay}" Command="{Binding UpdateFilledFieldsCommand}"/> 

BibTexFields 是我的 ViewModel 的一个属性,它也是我的 DataContext。 UpdateFilledFieldsCommand也是如此

XAML:

xmlns:vm="using:StudyConfigurationClient.ViewModels"
mc:Ignorable="d" d:DataContext="{d:DesignInstance vm:CreateStudyViewModel}">

<Grid x:Name="FieldOuter">
    <Border BorderBrush="Gray" BorderThickness="2" Margin="0, 0, 5, 0">

视图模型:

private ObservableCollection<ChosenField> _bibTexFields;
public ObservableCollection<ChosenField> BibTexFields
        {
            get { return _bibTexFields; }
            set
            {
                _bibTexFields = value;
                OnPropertyChanged();
            }
        }

我想要做的是从ListView 内部访问ViewModel,这样我就可以使用绑定到UpdateFilledFieldsCommand 属性的Command

我已尝试研究 RelativeSource 绑定,但似乎无法使其工作。尝试将其绑定到 DataContext 也不起作用。

【问题讨论】:

    标签: c# xaml listview mvvm uwp


    【解决方案1】:

    您也可以使用 ElementName:

     <CheckBox HorizontalAlignment="Right" IsChecked="{Binding IsChecked, Mode=TwoWay}" Command="{Binding DataContext.UpdateFilledFieldsCommand, ElementName=BibTexFields}"/>
    

    但是,RelativeSource 也应该可以工作。通过快速搜索,我发现了这个:How do I use WPF bindings with RelativeSource? 虽然我不知道 UWP 应用程序中是否存在所有功能,但它看起来不错。

    【讨论】:

    • 谢谢,完成了!
    最近更新 更多