如何在 dataTemplate 中为 WPF 工具包自动完成框设置项目源

How to Set Item source for WPF toolkit auto complete box inside dataTemplate

我有以下列表框

<ListBox x:Name="lbListItems"
        <ListBox.ItemTemplate>
            <DataTemplate>
                <ToggleButton x:Name="btnItem">
                    <StackPanel Orientation="Horizontal" Width="956">
                        <toolkit:AutoCompleteBox x:Name="acbItem"</toolkit:AutoCompleteBox>
                    </StackPanel>
                </ToggleButton>
            </DataTemplate>
        </ListBox.ItemTemplate>
</ListBox>

如何在代码隐藏中为 acbItem 设置 ItemsSource? 我无法访问它!

使用Loaded事件是一个解决方案。

<toolkit:AutoCompleteBox Loaded="myControl_Loaded" ...

private void myControl_Loaded(object sender, RoutedEventArgs e)
{
    toolkit:AutoCompleteBox myCombo = sender as toolkit:AutoCompleteBox; 
    // Do things..
}

但最好使用 MVVM 方法从 XAML

设置 ItemsSource

I bind the ItemsSource property for the Listbox but it does not work, If I put the Listbox out of template it works !

那么你应该指定一个RelativeSource的绑定:

<toolkit:AutoCompleteBox x:Name="acbItem" 
   ItemsSource="{Binding DataContext.YourItemsSourceCollection, RelativeSource={RelativeSource AncestorType=ListBox}}" />

只需将 "YourItemsSourceCollection" 替换为要绑定的属性的实际名称并保留其余部分。