1 回答

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超17個(gè)贊
你可以發(fā)揮一點(diǎn)創(chuàng)意來解決這個(gè)問題。假設(shè)您有一個(gè)寬度僅為 60 像素的組合框。因此,您希望組合項(xiàng)顯示為完整的州名稱和縮寫,例如CA - California,但如果選擇,您只需要縮寫。CA。
我聲明一個(gè)類來代表一個(gè)狀態(tài),如下所示:
public class State
{
public string ShortName { get; set; }
public string FullName { get; set; }
private string _displayName;
public string DisplayName
{
set
{
_displayName = value;
}
get
{
if (string.IsNullOrEmpty(_displayName))
return string.Format("{0} - {1}", ShortName, FullName);
else
return _displayName;
}
}
}
技巧是您用來DisplayName在組合框中顯示項(xiàng)目。然后,在getof中DisplayName,如果它已經(jīng)有值,則返回它,如果沒有,則連接狀態(tài)的短名稱和全名稱。
然后,當(dāng)您進(jìn)行數(shù)據(jù)綁定時(shí),您將擁有一個(gè)狀態(tài)列表以及SelectedState,并且在該屬性的設(shè)置器中,您將DisplayName設(shè)為ShortName。
所以,我的XAML:
<Grid>
<ComboBox ItemsSource="{Binding States}"
SelectedValue="{Binding SelectedState}"
DisplayMemberPath="DisplayName"
Name="CmbStates" Width="60" Height="32"/>
</Grid>
然后,在我的代碼中:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private List<State> _states;
public List<State> States
{
get { return _states; }
set
{
_states = value;
OnPropertyChanged("States");
}
}
private State _selectedState;
public State SelectedState
{
get { return _selectedState; }
set
{
_selectedState = value;
SelectedState.DisplayName = SelectedState.ShortName;
OnPropertyChanged("SelectedState");
}
}
public MainWindow()
{
InitializeComponent();
States = new List<State>
{
new State() { FullName = "California", ShortName = "CA" },
new State() { FullName = "New York", ShortName = "NY" },
new State() { FullName = "Oregon", ShortName = "OR" }
};
DataContext = this;
}
}
現(xiàn)在列表中應(yīng)該有完整的串聯(lián)名稱:
但只有選擇時(shí)的縮寫:
- 1 回答
- 0 關(guān)注
- 229 瀏覽
添加回答
舉報(bào)