Wpf来自数据库绑定的C#combobox itemssource [英] Wpf C# combobox itemssource from database binding
问题描述
好的,这就是问题 - 我会尽力解释它。
我有两种方法从数据库中提取两个不同的字段/值:类型和状态。这些方法正在运行并为每个方法输出正确的值。在XAML页面上,我有三个组合框。示例:
Ok, here's the problem - and I'll do my best to actually explain it.
I have two methods pulling two different fields/values form the database: Type and Status. The methods are working and oulling the correct values for each. On the XAML page, I have three comboboxes. Example:
<ComboBox x:Name="CbType" HorizontalAlignment="Right" Margin="0,10,18.2,0" VerticalAlignment="Top" Width="120" ItemsSource="{Binding}" />
<ComboBox x:Name="CbStatus" HorizontalAlignment="Left" Margin="89,91,0,77.4"
Width="120" ItemsSource="{Binding}" d:LayoutOverrides="Height" />
问题是ItemsSource ={Binding}。我认为,绑定应该看起来像ItemsSource ={Binding Type}和ItemsSource ={Binding Statuses}。我无法弄清楚如何将这个名称设置为绑定。如果没有为每个Binding提供不同的值,我在组合框中根本没有得到任何值。如果我在XAML中取出第二个方法和第二个ItemSource,它只适用于其中一个组合框。我认为代码不知道如何区分两者,那么如何帮助它理解呢? :)
以下是该方法的示例:
The problem is the ItemsSource="{Binding}". Binding, I think, should look something like ItemsSource="{Binding Type}" and ItemsSource="{Binding Statuses}". I can't figure out how to set this "names" to the binding. Without suppling a different value for each Binding, I get no values at all in the combobox. If I take out the second method and second ItemSource in the XAML, it works for only one of the comboboxes. I think the "code" doesn't know how to differeniate between the two, so how to do I help it understand? :)
Here is an example of the method:
public void GetAddrTypes()
{
//***Set Variables***
var preSql = Settings.Default.GetAddrTypes;
var sql = preSql;
Log.Debug("SP: " + preSql + " for GetAddrTypes()");
Log.Debug("Dbconn called and created for GetAddrTypes()");
var connectionString = Settings.Default.Dbconn;
using (var conn = new SqlConnection(connectionString))
//using (var cmd = new SqlCommand(sql, conn))
{
try
{
conn.Open();
var adpter = new SqlDataAdapter(sql, conn);
var ds = new DataSet();
adpter.Fill(ds);
CbType.DataContext = ds.Tables[0];
CbType.DisplayMemberPath = "AddrTypeCode";
CbType.SelectedValuePath = "AddrTypeCode";
Log.Debug("Command executed and reader completed for GetAddrTypes()");
}
catch (SqlException ex)
{
// Build custom message box for exception upload
var msg = ex.ToString();
var title = DataLogic.Properties.Resources.CustomMsgBxTitle;
MessageBoxManager.Ok = "Copy";
MessageBoxManager.Cancel = "Ignore";
MessageBoxManager.Register();
var result = MessageBox.Show(msg, title, MessageBoxButtons.OKCancel,
MessageBoxIcon.Hand);
switch (result)
{
case System.Windows.Forms.DialogResult.OK:
Clipboard.SetText(msg);
break;
case System.Windows.Forms.DialogResult.Cancel:
break;
}
MessageBoxManager.Unregister();
Log.Error("Exception Thrown: " + msg + " - for while calling GetAddrTypes");
}
finally
{
Log.Info("Closing SQL Connection for GetAddrTypes()");
}
}
}
这是页面加载
Here is the Page Load
private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
{
TbId.Text = Idval;
CbType.SelectedValue = Typeval;
TbDesc.Text = Descval;
CbStatus.SelectedValue = Statval;
CbSysReq.SelectedValue = Sysreqval;
GetAddrTypes();
GetStatusCodes();
}
我尝试过:
public ObservableCollection<> 名字{得到;组; }
但这些是我正在调用的类。
What I have tried:
public ObservableCollection<> "name" { get; set; }
But these are classes I'm calling.
推荐答案
绑定的基本原理是使用列表在视图模型中创建数据。我将在这里解释一下。
1.)创建一个示例类:
Hi,
The basic of binding this would be using a list to create the data in view model. I will try to explain it here.
1.) Create a sample class :
public class ComboData : INotifyPropertyChanged
{
private string _text { get; set; }
private string _values { get; set; }
public string Text
{
get { return _text; }
set
{
_text = value;
OnPropertyChanged("Text");
}
}
public string Values
{
get { return _values; }
set
{
_values = value;
OnPropertyChanged("Value");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
2.)在你的班级中添加两个列表的属性:
2.) In your class add the properties for two lists:
List<ComboData> _typeList = new List<ComboData>();
public List<ComboData> TypeList
{
get { return _typeList; }
set
{
_typeList = value;
RaisePropertyChanged(() => TypeList);
}
}
List<ComboData> _statusList = new List<ComboData>();
public List<ComboData> StatusList
{
get { return _statusList; }
set
{
_statusList = value;
RaisePropertyChanged(() => StatusList);
}
}
这两个属性在我的视图模型中。如果你想知道什么是RaisePropertyChanged(),它是我的ViewModelBase的实现。
我的示例ViewModelBase可以是:
These two properties are in my view model. If you are wondering what is RaisePropertyChanged() here, it is the implementation for my ViewModelBase.
My sample ViewModelBase can be like:
public abstract class ViewModelBase : INotifyPropertyChanged
{
protected void RaisePropertyChanged<T>(Expression<Func<T>> action)
{
var propertyName = GetPropertyName(action);
RaisePropertyChanged(propertyName);
}
private static string GetPropertyName<T>(Expression<Func<T>> action)
{
var expression = (MemberExpression)action.Body;
var propertyName = expression.Member.Name;
return propertyName;
}
public void RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
3.)在视图模型构造函数中创建示例数据。如果你没有使用mvvm方法,请在你的Loaded事件中创建:
3.) Create a sample data in your view model constructor. If you are not using mvvm approach, create this in your Loaded event:
TypeList.Add(new ComboData {Text = "1234", Values = "1234"});
TypeList.Add(new ComboData {Text = "1234", Values = "41234"});
StatusList.Add(new ComboData {Text = "agfasd", Values = "asgas"});
StatusList.Add(new ComboData {Text = "ag", Values = "asdg"});
基本上,这里我们有一个text属性,用于显示绑定值为其成员路径的值。
4.)在你的xaml中添加ComboBox:
So basically, here we have a text property that will be for display binded with a value for its value member path.
4.) Add the ComboBox in your xaml:
<combobox grid.row="1" grid.column="1" x:name="CbType" itemssource="{Binding TypeList}" displaymemberpath="Text" selectedvaluepath=" Values" xmlns:x="#unknown" />
这应该有效。
尝试在谷歌搜索并查看绑定组合框的基础知识。
希望这有帮助!
This should work.
Try searching on google and see what are basics of binding a combobox.
Hope this helps !
这篇关于Wpf来自数据库绑定的C#combobox itemssource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!