我創建了一些包裝一些標準控件的用戶控件,例如:一個文本框/組合框+圖像+文本塊。我正在嘗試使用AutoCompleteBox做同樣的事情,目前失敗... 項目列表顯示正常,我可以選擇na項目,但是這不會觸發對SelectedItem的更改。我使用幾乎相同的代碼組合框,所以不知道有什麼問題...wpf autocompletebox綁定
無論如何,我已經玩過AutoCompleteBox上的ValueMemberPath/ValueMemberBinding,但不知道如果這是要走的路。
UserControl的XAML:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<Grid Grid.Column="0" Margin="0,0,2,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Source="{Binding ElementName=ACProperty, Path=ImageSource}" VerticalAlignment="Center"
MaxHeight="30" MaxWidth="30" Margin="1" Grid.Column="0" RenderOptions.BitmapScalingMode="HighQuality"/>
<TextBlock Text="{Binding ElementName=ACProperty, Path=Label}" VerticalAlignment="Center"
HorizontalAlignment="Left" Grid.Column="1" Margin="1" TextWrapping="Wrap" Width="100" />
</Grid>
<toolkitInput:AutoCompleteBox FilterMode="ContainsOrdinal" IsTextCompletionEnabled="True"
ItemsSource="{Binding ElementName=ACProperty, Path=ItemsSource}"
SelectedItem="{Binding ElementName=ACProperty, Path=SelectedItem}"
MinimumPrefixLength="2"
MinimumPopulateDelay="300"
VerticalAlignment="Center"
HorizontalAlignment="Stretch" Grid.Column="1" Margin="1,1,2,1" />
</Grid>
背後的代碼:
public static DependencyProperty LabelProperty = DependencyProperty.Register(
"Label", typeof(string), typeof(AutoCompleteProperty));
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(object), typeof(AutoCompleteProperty));
public static readonly DependencyProperty SelectedItemProperty =
DependencyProperty.Register("SelectedItem", typeof(object), typeof(AutoCompleteProperty),
new FrameworkPropertyMetadata() { BindsTwoWayByDefault = true });
public static DependencyProperty ImageSourceProperty = DependencyProperty.Register(
"ImageSource", typeof(string), typeof(AutoCompleteProperty));
public object ItemsSource
{
get
{
return (object)GetValue(ItemsSourceProperty);
}
set
{
SetValue(ItemsSourceProperty, value);
}
}
public object SelectedItem
{
get
{
return (object)GetValue(SelectedItemProperty);
}
set
{
SetValue(SelectedItemProperty, value);
}
}
public string Label
{
get
{
return (string)GetValue(LabelProperty);
}
set
{
SetValue(LabelProperty, value);
}
}
public string ImageSource
{
get
{
return (string)GetValue(ImageSourceProperty);
}
set
{
SetValue(ImageSourceProperty, value);
}
}
而且在用戶控件/窗口,在這裏我想用它:
<cont:AutoCompleteProperty Label="Product Category"
ItemsSource="{Binding Path=ProductCategories}"
SelectedItem="{Binding Path=ProductCategory}"
ImageSource="..."/>
感謝您的所有幫助,但實際上這是另一回事,將SelectedItem綁定模式設置爲TwoWay做了竅門,儘管我不確定爲什麼如果在BindsTwoWayByDefault設置爲True ...標記爲您的努力的答案。 – hyp