DependencyProperty绑定不会更新到集合CurrentItem

时间:2012-08-08 02:21:33

标签: c# .net wpf xaml binding

我正在尝试将依赖项属性绑定到集合的当前选择,并且出于我无法理解的原因,绑定在集合更改时不会更新。

在下面的示例中,我展示了两个示例。一个是正​​确更新(在文本块/运行中),另一个只显示初始元素,并且在数据网格选择更改时不会更改。

<Grid>
    <Grid.Resources>
        <CollectionViewSource Source="{Binding Path=List}" x:Key="myViewModel"/>
        <my:UpdateNotWorking MyObjModel="{Binding Source={StaticResource myViewModel}, Path=CurrentItem}" x:Key="updateNotWorking" />
    </Grid.Resources>

    <DataGrid ItemsSource="{Binding Source={StaticResource myViewModel}}" Name="mylistbox"/>
    <TextBlock TextWrapping="Wrap" FontWeight="Bold" Foreground="#FF50CEFF" FontSize="24" TextAlignment="Center" Height="75">
            <Run Text="{Binding Source={StaticResource myViewModel}, Path=text}" Foreground="#FF00E200" />
    </TextBlock>
    <TextBox Text="{Binding Source={StaticResource updateNotWorking}, Path=MyObjModel.text}" Height="22"/>

</Grid>

此示例中的依赖项属性是“UpdateNotWorking”依赖项对象上的“MyObjModel”,它是从xaml代码实例化的。

我很感激有关我的财产未正确更新的任何信息。

Example Project

1 个答案:

答案 0 :(得分:0)

将此XAML粘贴到您的MainWindow中。

  <Grid>
    <Grid.Resources>
      <CollectionViewSource Source="{Binding Path=List}" x:Key="myViewModel" />
      <my:UpdateNotWorking x:Key="updateNotWorking" />
    </Grid.Resources>

    <DataGrid ItemsSource="{Binding Source={StaticResource myViewModel}}" Name="mylistbox"
              SelectedItem="{Binding Source={StaticResource updateNotWorking}, Path=MyObjModel, UpdateSourceTrigger=PropertyChanged}" />
    <TextBlock TextWrapping="Wrap" FontWeight="Bold" Foreground="#FF50CEFF" FontSize="24" TextAlignment="Center"
               Height="75">
      <Run Text="{Binding Source={StaticResource myViewModel}, Path=text}" Foreground="#FF00E200" />
    </TextBlock>
    <TextBox Text="{Binding Source={StaticResource updateNotWorking}, Path=MyObjModel.text, UpdateSourceTrigger=PropertyChanged}"
             Height="22" />

  </Grid>

它现在正在做的是根据DataGrid的updateNotWorking设置MyObjModel的{​​{1}}属性,并将SelectedValue设置为UpdatePropertyTrigger以查看更改立即。我们不再需要通过List的CurrentItem来定义PropertyChanged的属性,因为它不会仅通过使用DataGrid选择它来改变。您可以保持设置,但不需要它,因为我们使用updateNotWorking进行所有手动操作。

相关问题