Roc*_*aul 2 c# data-binding wpf xaml combobox
我知道这是基本的,但我正在从vb.net跳转到C#,而我在vb.net中使用的方法似乎并不起作用.我用自定义类服务创建了一个.dll.
在我的项目中,我正在使用Service实例填充ObservableCollection.我想在XAML(WPF)中使用DisplayMemberPath在组合框中显示实例.
我的服务实例正在填充ComboBox,但每个项目的显示都是空白的; 我只是得到一堆空行可供选择.
我已经尝试了这个,有没有在类本身上实现INotifyPropertyChanged,虽然我不认为此时应该是必要的,因为我仍然非常在第1方.
这是我的代码:
<Grid>
<ComboBox Name="TopService"
VerticalAlignment="Top"
ItemsSource="{Binding}"
DisplayMemberPath="{Binding ServCode}"></ComboBox>
</Grid>
Run Code Online (Sandbox Code Playgroud)
这是我的代码背后:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Execute();
}
private void Execute()
{
SA.franchiseID = "HOL010";
ObservableCollection<Service> ocService = Service.InitializeServiceList();
TopService.DataContext = ocService;
}
}
Run Code Online (Sandbox Code Playgroud)
和类的代码(通过.dll引用)
public class Service : INotifyPropertyChanged
{
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
protected void Notify(string propertyName)
{
if (this.PropertyChanged != null)
{ PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); }
}
#endregion
private string servCode;
public string ServCode
{
get { return servCode; }
set { servCode = value; Notify("ServCode"); }
}
public string programCode = "";
public int roundNum = 0;
public static ObservableCollection<Service> InitializeServiceList()
{
ObservableCollection<Service> oc = new ObservableCollection<Service>();
using (SA s = new SA())
{
s.SqlString = @"select
ps.serv_code
,pc.prgm_code
,ps.round
from prgmserv as ps
inner join prgmcd as pc on pc.progdefid = ps.progdefid
where pc.available = 1";
s.reader = s.command.ExecuteReader();
Service newService;
while (s.reader.Read())
{
newService = new Service();
newService.servCode = s.reader["serv_code"].ToString();
newService.programCode = s.reader["prgm_code"].ToString();
newService.roundNum = Convert.ToInt32(s.reader["round"].ToString());
oc.Add(newService);
newService = null;
}
return oc;
}
}
}
Run Code Online (Sandbox Code Playgroud)
DisplayMemberPath是一个字符串.你没有给它绑定一个属性; 你只需给它一个属性的路径,然后通过反射查找它.
试试这个:
DisplayMemberPath="ServCode"
Run Code Online (Sandbox Code Playgroud)
你在做将使利用价值的ServCode作为DisplayMemberPath; 如果是ServCode 12,它会12在组合框中找到每个项目上命名的属性- 不是你的意图,我敢肯定.
| 归档时间: |
|
| 查看次数: |
494 次 |
| 最近记录: |