0

这是我的用户控制代码:

<UserControl .... x:Name="UserControl" />
<Grid x:Name="LayoutRoot" DataContext="{Binding ElementName=UserControl, Mode=OneWay}" >
    <DataGrid ItemsSource="{Binding Websites}" AutoGenerateColumns="False" CellEditEnding="DataGrid_CellEditEnding" BeginningEdit="DataGrid_BeginningEdit">
        <DataGrid.Columns>
            ...
            <DataGridTemplateColumn>
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button .... CommandParameter="{Binding}" >
                            <Button.Content>
                                <Image Source="./../Images/close.png" Width="15"></Image>
                            </Button.Content>
                            <Button.Command>                                                            
                                <MultiBinding Converter="{StaticResource TriggerConverter}">
                                    <Binding ElementName="UserControl" Path="DataContext.DeleteCommand" >
                                        </Binding>
                                    <Binding />
                                </MultiBinding> 
                            </Button.Command>                               
                        </Button>
                    </DataTemplate>                                             
                </DataGridTemplateColumn.CellTemplate>                                          
            </DataGridTemplateColumn>
        </DataGrid.Columns>         
    </DataGrid>     
</Grid>

    CDeleteCommand dc = null;

    public ICommand DeleteCommand
    {
        get 
        {
            if (dc!=null)
            {
                return dc;
            }
            return dc = new CDeleteCommand() { Pannel = this };
        }
    }

我在 DeleteCommand.get 有一个断点,它永远不会被触发。

这是我得到的绑定错误:

Cannot find source for binding with reference 'ElementName=UserControl'. 
BindingExpression:Path=DataContext.DeleteCommand; DataItem=null; target element is
 'Button' (Name=''); target property is 'Command' (type 'ICommand')

为什么不,我该如何解决?

4

1 回答 1

1

UserControl无法从 访问DataGridTemplateColumn.CellTemplate

你可以试试RelativeSource

"{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGrid}},
                                Path=DataContext.DeleteCommand}"

或将您的 ViewModel 添加到资源并通过StaticResource

"{Binding DeleteCommand, Source={StaticResource ViewModel}}"

下面是 MultiBinding 的样子:

<MultiBinding Converter="{StaticResource TriggerConverter}">
    <Binding RelativeSource="{RelativeSource AncestorType={x:Type DataGrid}}" 
        Path="DataContext.DeleteCommand" />
    <Binding />
</MultiBinding> 
于 2012-04-23T12:12:03.117 回答