祖先在ListView数据模板中绑定ComboBox ItemsSource

时间:2016-11-07 08:12:29

标签: c# wpf listview combobox datatemplate

我认为我有这个代码。

<Grid DataContext="{Binding Main, Source={StaticResource Locator}}" Background="White">
    <ListView ItemsSource="{Binding SelectedMethod.Commands}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ComboBox ItemsSource="{Binding  RelativeSource={RelativeSource AncestorType={x:Type Grid},AncestorLevel=1}, 
                                           Path=DataContext.MethodEventFunctions}"
                    SelectedValue="{Binding FunctionName, Mode=TwoWay}"/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>

这个代码背后:

public MethodViewModel SelectedMethod
{
    get { return _selectedMethod; }
    set
    {
        _selectedMethod = value;
        RaisePropertyChanged();
    }
}        

public List<string> MethodEventFunctions { get; private set; }

public class MethodViewModel
{
    public List<MethodBindingViewModel> Commands
    {
        get { return _commands; }
        set
        {
            _commands = value;
            RaisePropertyChanged();
        }
    }
}

我在MethodEventFunctions构造函数中填充ViewModel。然后我选择方法,但ComboBox保持为空。 但是,如果我将ListView更改为ListBox,那就没关系了。哪里有问题?

这段代码也给了我一个空的ComboxBox。

 <Grid Name="GridMain" DataContext="{Binding Main, Source={StaticResource Locator}}" Background="White">
    <ListView ItemsSource="{Binding SelectedMethod.Commands}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Name" Width="120">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <ComboBox ItemsSource="{Binding  RelativeSource={RelativeSource AncestorType={x:Type Grid},AncestorLevel=1}, 
                                       Path=DataContext.MethodEventFunctions}"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

0 个答案:

没有答案