【问题标题】:how to pass a view element to another view as command parameter?如何将视图元素作为命令参数传递给另一个视图?
【发布时间】:2019-12-11 00:01:39
【问题描述】:

我在 xaml 中有一个窗口:

<view:ToolBar DataContext="{Binding}"/>

<Grid>
    <ListView>
        <ListView.View>
           <GridView>
               <GridViewColumn>
               ....//all the columns
           </GridView>
        </ListView.View>
    </ListView>
</Grid>

工具栏是一个继承自用户控件的类。在toolbar.xaml 中,我有一个按钮,它有一个命令。

<ToggleButton Style="{DynamicResource ToggleButtonStyle}" 
              IsChecked="{Binding Checked}"
              Command="{x:Static ui:GridHelper.UpdateColumns}">
</ToggleButton>

每次单击该按钮时,我都想将列表视图的列标题传递给命令。但我不知道如何连接工具栏和列表视图,因为它们完全分开。有任何想法吗?谢谢!

【问题讨论】:

  • 也许你应该使用一个视图模型来保存这种信息,比如列标题和列数据。其他控件可以轻松绑定到这些数据。

标签: c# wpf xaml command


【解决方案1】:

首先,您需要在 ToolBar 控件中添加一个新的 DependencyProperty。您可以在此处阅读有关 DependencyProperties 的信息:

https://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/dependency-properties-overview

在您的情况下,此 DependencyProperty 将是一个属性,它将是一个列列表。由于它是一个 DependencyProperty,您将能够在 Xaml 中将一个值绑定到它,并从您的 ToolBar 控件中检索这些列。

现在,关于如何将列列表绑定到您的 DependencyProperty,您有几个选择。第一个是将其直接绑定到您的 ListView。它看起来像这样:

<view:ToolBar YourDependencyProperty={Binding TheListOfColumns, ElementName=MyGridView}"/>

<Grid>
    <ListView>
        <ListView.View>
           <GridView x:Name="MyGridView">
               <GridViewColumn>
               ....//all the columns
           </GridView>
        </ListView.View>
    </ListView>
</Grid>

另一个选项类似于他对您的问题的评论中描述的 BionicCode,方法是将列保留在 ViewModel 中并绑定到 ViewModel 属性。但为此,您必须在 ViewModel 中创建列,而不是在 Xaml 中。绑定看起来像这样:

<view:ToolBar YourDependencyProperty={Binding ListOfColumnsPropertyFromTheViewModel}"/>

希望有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 2022-06-10
    • 1970-01-01
    相关资源
    最近更新 更多