![](/img/trans.png)
[英]WPF `ComboBox` ItemsSource property is changed the SelectedItem property is being set to null
[英]SelectedItem in ComboBox not being set to data field
由於某種原因,SelectedItem並未設置為數據庫中的任何字段。
XAML:
<!-- Type -->
<Label Grid.Column="0" Grid.Row="1"
Style="{StaticResource FormLabelStyle}"
Content="Type:"/>
<Border Grid.Column="1" Grid.Row="1"
Style="{StaticResource FormBorderStyle}"
Width="350">
<ComboBox x:Name="codeType" Margin="5" Padding="0"
FontSize="20" FontFamily="Arial" BorderThickness="0"
BorderBrush="Transparent" Background="White"
Text="{Binding CodType}" SelectedItem="{Binding CodType}">
<ComboBoxItem Content="C"/>
<ComboBoxItem Content="C++"/>
<ComboBoxItem Content="C#"/>
<ComboBoxItem Content="PL/SQL"/>
<ComboBoxItem Content="SQL"/>
<ComboBoxItem Content="HTML"/>
<ComboBoxItem Content="XAML"/>
<ComboBoxItem Content="Unix Shell Script"/>
</ComboBox>
</Border>
背后的代碼:
public ChangeCode(CodeRecord codRec)
{
_codeRecord = codRec;
this.DataContext = _codeRecord;
InitializeComponent();
}
顯示屏幕時,我希望選擇當前的CodType字段。 調試表明它確實不為null,並且是comboboxitems之一。 組合框顯示未選擇任何內容。 我究竟做錯了什么?
創建ComboBoxItem時,內容文本為字符串,字符串類沒有顯示文本的屬性,它可能允許您使用string.ToString()進行選擇,但是在顯示屏幕時,它沒有屬性以匹配ComboBox項並顯示SelectedValue中的內容。 為了解決這個問題,您必須創建一個新類ComboBoxItemString,如下所示,其屬性為ValueString
public class ComboBoxItemString
{
public string ValueString { get; set; }
}
然后在資源中創建ComboBoxItemString的數組(CodeTypesList),如下所示,並將其綁定到ItemsSource,然后在DisplayMemberPath和SelectedValuePath中使用poperty ValueString。
<Border Grid.Column="1" Grid.Row="1"
Style="{StaticResource FormBorderStyle}"
Width="350">
<Border.Resources>
<x:Array x:Key="CodTypesList" Type="local:ComboBoxItemString">
<local:ComboBoxItemString ValueString = "C"/>
<local:ComboBoxItemString ValueString = "C++"/>
<local:ComboBoxItemString ValueString = "C#"/>
<local:ComboBoxItemString ValueString = "PL/SQL"/>
<local:ComboBoxItemString ValueString = "SQL"/>
<local:ComboBoxItemString ValueString = "HTML"/>
<local:ComboBoxItemString ValueString = "XAML"/>
<local:ComboBoxItemString ValueString = "Unix Shell Script"/>
</x:Array>
</Border.Resources>
<ComboBox x:Name="codeType" Margin="5" Padding="0"
FontSize="20" FontFamily="Arial" BorderThickness="0"
BorderBrush="Transparent" Background="White"
SelectedValue="{Binding CodType}"
ItemsSource="{StaticResource CodTypesList}"
DisplayMemberPath="ValueString" SelectedValuePath="ValueString" />
</Border>
現在,當您進入屏幕時,它應該使用該屬性在ComboBox中顯示先前選擇的值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.