dynamic combobox and select particular item in combobox to execute certain things - c#

I have a string array which contains filenames. a number of filenames vary depending on what endusers select. I would like know how to populate the string array onto combobox. Thanks for your help in advance,

Your requirement is simple. Create an ObservableCollection<string> named Items and fill it with your filenames:
public ObservableCollection<string> Items
{
get { return items; }
set { items = value; NotifyPropertyChanged("Items"); } }
}
Make sure that you implement the INotifyPropertyChanged Interface correctly in the class that has the property. Next, simply data bind this property to the ComboBox.ItemsSource property in XAML:
<ComboBox ItemsSource="{Binding Items}" />
Finally, ensure that you have set the DataContext of the control with the XAML to an instance of the class with the property:
Either:
DataContext = this; // if properties are defined in code behind
Or:
DataContext = new ClassWithProperty();

Here a simple way to achieve this
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string[] files = new string[]{};
ObservableCollection<string> observableCollection = new ObservableCollection<string>(files);
comboBox1.ItemsSource = observableCollection;
}
}

If you have your full array of filenames, you may want to try something like this:
for(int i = 0; i < myStringArray.Length; i++)
{
ComboBox1.Items.Add(myStringArray[i]);
}
This should add all of the filenames into the combobox ComboBox1.

Related

How to Bind an ObservableCollection of XyDataSeries using an Attached Property

I am creating a Charting application using SciChart.
I have added a chart modifier class which allows editing of the chart data but only the data currently displayed. I need to extend this class so that the full ObservableCollection of each XyDataSeries can be accessed.
I have implemented an attached property which I can bind to in the MainWindow DataContext however whenever I run the application the collection is showing as null in the modifier class. Please can you advise. Thanks
public class MoveBlockModifier : ChartModifierBase
{
public static readonly DependencyProperty XyFGDataProperty = DependencyProperty.RegisterAttached("XyFGData", typeof(ObservableCollection<XyDataSeries<double,double>>), typeof(MoveBlockModifier), new FrameworkPropertyMetadata(new ObservableCollection<XyDataSeries<double,double>>()));
public ObservableCollection<XyDataSeries<double, double>> XyFGData
{
get { return (ObservableCollection < XyDataSeries<double, double>>)GetValue(XyFGDataProperty); }
set { SetValue(XyFGDataProperty, value); }
}
public MoveBlockModifier()
{
_ghostSeries = new FastLineRenderableSeries()
{
Stroke = Colors.Black,
DataSeries = editingSeries,
Name = "GhostSeries",
StrokeThickness = 1,
Opacity = 0.75,
};
}
}
Public Class MainWindow: Window, INotifyPropertyChanged
{
private ObservableCollection<XyDataSeries<double, double>> _xyFGData;
public ObservableCollection<XyDataSeries<double, double>> XYFGData
{
get { return _xyFGData; }
set { _xyFGData = value; OnPropertyChanged("XYFGData"); }
}
}
XAML of MainWindow
<s:SciChartSurface x:Name="Chart2">
<s:SciChartSurface.ChartModifier>
<local:MoveBlockModifier FixStart="{Binding FixStart}" FixEnd="{Binding FixEnd}"
IsEnabled="{Binding ChartTwoMoveBlockEnabled, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
XyFGData="{Binding XYFGData, Mode=TwoWay}" />
</s:ModifierGroup>
</s:SciChartSurface.ChartModifier>
</s:SciChartSurface>
The question above seems incomplete / has some errors. You mention an attached property, which you define as this
public static readonly DependencyProperty XyFGDataProperty = DependencyProperty.RegisterAttached("XyFGData", typeof(ObservableCollection<XyDataSeries<double,double>>), typeof(MoveBlockModifier), new FrameworkPropertyMetadata(new ObservableCollection<XyDataSeries<double,double>>()));
public ObservableCollection<XyDataSeries<double, double>> XyFGData
{
get { return (ObservableCollection < XyDataSeries<double, double>>)GetValue(XyFGDataProperty); }
set { SetValue(XyFGDataProperty, value); }
}
...
but this isn't the way to define attached properties in WPF. Follow the MSDN documentation for how to register an attached property.
Secondly, you define a default value of new ObservableCollectionXyDataSeries<double, double> in your FrameworkPropertyMetadata, but this is a bad idea, because you will share one instance of ObservableCollectionXyDataSeries<double, double> statically across all instances of MoveBlockModifier. Have a look at Where to initialize reference type dependency properties for a custom control?
Lastly its an attached property that you want to define but in XAML you are not using it like an attached property.
This part:
is incorrect. See how an attached property is attached in XAML here.
Finally you bind MoveBlockModifier.XyFGData to a property XYFGData in your main window but the DataContext of the MoveBlockModifier might not be MainWindow.
I suggest starting again and fixing these errors!

Bind list from class to combobox

I'm currently writing a pretty small program in C# and have this list that I want to bind to a combobox. Now, I've put that list in a class, and want to bind that list to a combobox. The code below shows how far I've come so far:
Form
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Locaties locaties = new Locaties();
List<string> listofLocaties = locaties.retrieveLocations();
cboxLocToevoegen.DataSource = ???;
cboxLocOverzicht.DataSource = ???;
}
}
Class
class Locaties
{
public List<string> retrieveLocations()
{
List<string> LocatieList = new List<string>();
LocatieList.Add("Koelkast");
LocatieList.Add("Keukenlade");
LocatieList.Add("Voorraadruimte");
LocatieList.Add("Overige");
return LocatieList;
}
}
Now, I'm gonna be honest with you: my knowledge and experience with classes and methods is not perfect. That's why the solution might probably be simpler than I think. Please don't judge me on that, I'm still learning!
Anyway, I hope anyone can help me out with this!
Simply
cboxLocToevoegen.DataSource = listofLocaties ;
or directly
cboxLocToevoegen.DataSource = locaties.retrieveLocations();
you can also bind directly to a list of Locaties and then choose the property to display in the CB :
List<Locaties> listofLocaties = new List<Locaties>();
...
//Populate the list
...
cboxLocToevoegen.DataSource = listofLocaties ;
cboxLocToevoegen.DisplayMember = [a property of Locaties class];
// and the value of the CB could be another property of Locaties class:
cboxLocToevoegen.ValueMember = [the value property of Locaties class];
But ofc you have to write a new Locaties class :)

Data-binding ObservableCollection<T> with ComboBox doesn't work with Dependency Property

I have a list of objects (ObservableCollection subjectlist) and want to display them in a Combobox via data-binding and dependency property.
WPF Data Binding to a Combo Box
I searched on stackoverflow and tried to implement the solution of Craig Suchanec in the link above. (tried the whole day now and I just don't get what's wrong with my code)
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public static readonly DependencyProperty SubjectListProperty =
DependencyProperty.Register("SubjectList",
typeof(ObservableCollection<Subject>),
typeof(MainWindow));
private ObservableCollection<Subject> subjectList = new ObservableCollection<Subject>();
Initialization init1;
public ObservableCollection<Subject> SubjectList
{
get { return (ObservableCollection<Subject>)GetValue(SubjectListProperty); }
// get { return subjectList; }
}
public MainWindow()
{
init1 = new Initialization();
subjectList = init1.createMenuSubject();
InitializeComponent();
//this.comboBox.DataContext = SubjectList;
}
}
MainWindow.xaml
<Grid>
<ComboBox x:Name="comboBox" HorizontalAlignment="Left"VerticalAlignment="Top" Width="120" Margin="321,10,0,0"
ItemsSource="{Binding ElementName=mainWindow, Path=SubjectList}" DisplayMemberPath="Name"/>
</Grid>
It DOES work if I just set the DataContext and work without dependency property, but as soon as I try to use the dependency property for data-binding it does NOT and I don't see the significant difference between my implementation and the solution given in the link.
It would be much appreciated, if somebody could help me with this problem.
I can't see anywhere in your code where you are actually setting the value of the SubjectList property.
You are however setting the value of subjectList, but you're binding to SubjectList. Note the casing difference.
You should write:
public ObservableCollection<Subject> SubjectList
{
set { base.SetValue(SubjectListProperty, value); }
get { return (ObservableCollection<Subject>)base.GetValue(SubjectListProperty); }
}
instead of
public ObservableCollection<Subject> SubjectList
{
set { base.SetValue(SubjectListProperty, value); }
get { return subjectList; }
}
or any other ad hoc format. You are setting subjectList in your constructor MainWindow(), however, it will not set the value of SubjectList (with Capital S) and a property change event is never raised. Remove subjectList.
If you are wondering why the DataContext approach works, you should note it will work even if you do not use a DepenedencyProperty. However, if you implement INotifyPropertyChange, it will work with setting ElementName too.

Binding listbox from another project class

How can i bind a property ObservableCollection, to xaml listbox.
Collection is in another project. I already have datacontext = this for second property.
I have some project Data, there is a class with property ObservableCollection Values. I need to bind it to mainwindow's xaml listbox Values.
If you have a view model that implements INotifyPropertyChanged
you can add an additional property that wraps the property in your other class, you would then need to bind to this property e.g.
const string MY_COLLECTION = "MyObservableCollection";
ObservableCollection<someType> _myObservableCollection;
public ObservableCollection<someType> MyObservableCollection
{
get
{
return _myObservableCollection;
}
set
{
if (value == _myObservableCollection) return;
_myObservableCollection = value;
RaisePropertyChanged(MY_COLLECTION);
}
}
In your xaml set your binding to yourDataContext.MyObservableCollection, in your (e.g) constructor for your view model set the property to your other observable collection i.e.
MyObservableCollection = OtherClass.OtherObservableCollection
Obviously their types will need to match

Clear var defined in UserControl from main Form

I've a UserControl where I define some vars and also has some components like buttons, textbox and some others:
private List<string> bd = new List<string>();
private List<string> bl = new List<string>();
It's possible to access to those vars from namespace WindowsFormsApplication1? How? If I try to do this from private void recuperarOriginalesToolStripMenuItem_Click(object sender, EventArgs e) I got a error:
bl = new List<string>();
blYear.Enabled = true;
btnCargarExcel.Enabled = true;
filePath.Text = "";
nrosProcesados.Text = "";
executiontime.Text = "";
listBox1.DataSource = null;
What's the right way to do this?
EDIT: clarify
What I'm looking for is to clean values each time I access a menu item. For textBox and others components it works thanks to the suggestions made here but for List I don't know how to set it to null
you can always access any variable that you define, any control that you place on your UserControl at all those places, where you have placed your UserControl.
Just make sure, you have made your variables public and exposed your Controls through public properties i.e
suppose you have kept a TextBox on your UserControl for Names. In order to use it outside, you must expose it through a public property
public partial class myUserControl:UserControl
{
public TextBox TxtName{ get{ return txtBox1;}}
public ListBox CustomListBoxName
{
get
{
return ListBox1;
}
set
{
ListBox1 = value;
}
}
public List<object> DataSource {get;set;}
}
and you can use it on the form you have dragged this usercontrol i.e.
public partial form1: System.Windows.Forms.Form
{
public form1()
{
InitializeComponent();
MessageBox.Show(myUserControl1.TxtName.Text);
MessageBox.Show(myUserControl1.CustomListBoxName.Items.Count);
myUserControl1.DataSource = null;
}
}
similary you can expose your variables, through public properties. That way you can also control whether you want some of your variables to be readonly or what!
You need to expose a property and then access that property on the usercontrol-instance from your main form:
UserControl
public List<string> BD {get; set;}
Main form
MyUserControl.BD = new List<string>();

Categories

Resources