【问题标题】:C# WPF Binding path not working [duplicate]C#WPF绑定路径不起作用[重复]
【发布时间】:2017-11-15 20:58:40
【问题描述】:

我目前有一个绑定到对象集合的 ListBox,并为集合中的每个对象显示一个按钮。

XAML:

<Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>

    <ListBox x:Name="company_buttons"
             HorizontalContentAlignment="Left" VerticalContentAlignment="Top" 
             Padding="-2,-2,0,0" Height="280" Width="300" Background="{x:Null}" BorderBrush="{x:Null}" Margin="0,0,0,0" BorderThickness="0" 
             ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
             ItemsSource="{Binding Buttons_Binding}">

        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>

                    <Button Background="#FFFCC515" Style="{StaticResource RoundCorner}" FontFamily="Segoe UI" FontSize="16" FontWeight="Bold" TabIndex="0" 
                                CommandParameter="{Binding This_Works}"
                                Command="{Binding HELP WITH THIS}">
                        <StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Width="270" Height="44">
                            <Label HorizontalContentAlignment="Center" VerticalContentAlignment="Top" Margin="5,0,5,0" Height="21" Padding="0" Content="{Binding This_Works}"/>
                            <Label HorizontalContentAlignment="Center" VerticalContentAlignment="Top" Margin="5,0,5,0" Height="21" Padding="0" Content="{Binding This_Works}"/>
                        </StackPanel>
                    </Button>

                    <Label VerticalContentAlignment="Top" Margin="5,0,5,0" Height="19" Padding="0" Foreground="White" FontFamily="Segoe UI" FontSize="12" FontWeight="Bold" Content="{Binding Path}"/>

                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>

    </ListBox>

以下是绑定中用到的东西:

public class ButtonContent : INotifyPropertyChanged
{
 // stuff
}

public class MainWindowViewModel
{
    public static ObservableCollection<ButtonContent> Buttons_Binding
    {
 // stuff
    }

    public ICommand Command
    {
 // stuff
    }

我的问题是我不知道如何将按钮单击绑定到Command,因为它在集合Buttons_Binding 之外,因此不在同一个数据上下文中。我从示例中看到的所有东西以及我尝试过的东西都失败了。

【问题讨论】:

    标签: c# wpf xaml data-binding


    【解决方案1】:

    由于每个 Button 都绑定到 ListBoxItem 的 DataContext,它无法访问 ListBox 的 DataContext。但是,您可以在绑定中使用 RelativeSource 遍历可视化树。试试这个

    <Button ... 
            Command="{Binding Path=DataContext.Command,
                      RelativeSource={RelativeSource AncestorType=ListBox}}">
        ...
    </Button>
    

    【讨论】:

    • 那行得通。出于某种原因,我可以在搜索中找到答案。我还找到了一种非常笨拙的方法来让它工作。我将函数设为静态,然后执行此操作:Command="{Binding Source={x:Static local:MainWindowViewModel.Command}}"
    猜你喜欢
    • 1970-01-01
    • 2011-08-19
    • 2017-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    相关资源
    最近更新 更多