I initially add some string objects in a listBox and afterwards I want to set the Item that is selected:
List <string> CustName = new List<string>();
....///add items to CustName///...
listBox1.ItemsSource = CustName;
string selection = "myselection" ///this string is contained in CustName
listBox1.SelectedValue = selection;
However tha above doesn't work seens the selected Item is the first item of the listBox and not the one I try to set...
why not use binding, something like this.
XAML:
<ListBox ItemsSource={Binding CustName} SelectedItem={Binding MySelectedItem} />
then have a property
private string mySelectedItem;
public string MySelectedItem
{
get{return mySelectedItem;}
set
{
mySelectedItem=value;
RaisePropertyChanged("MySelectedItem");
}
if you want to set the SelectedItem manually in code, then just do MySelectedItem=yourItem;
Don't forget to set DataSource of the listbox and implement INotifyPropertChanged
XAML:
<Grid>
<ListBox HorizontalAlignment="Left" Name="listBox1" Height="100" Margin="310,172,0,0" VerticalAlignment="Top" Width="100"/>
</Grid>
CodeBehind.cs
public MainWindow()
{
InitializeComponent();
List<string> CustName = new List<string>();
CustName.Add("test1");
CustName.Add("test2");
CustName.Add("myselection");
listBox1.ItemsSource = CustName;
string selection = "myselection";
listBox1.SelectedItem = selection;
}
Related
I'm trying to use a ListBox to choose an entry and then display a picture belonging to this selected entry. But just at the beginning I got my first problem: filling the ListBox with binding is working, but if I click on one line in my running program, it doesn't select the line. I can just see the highlighted hover effect, but not select a line. Any ideas what my mistake could be?
This is my XAML:
<ListBox x:Name="entrySelection" ItemsSource="{Binding Path=entryItems}" HorizontalAlignment="Left" Height="335" Margin="428,349,0,0" VerticalAlignment="Top" Width="540" FontSize="24"/>
And in MainWindow.xaml.cs I'm filling the ListBox with entries:
private void fillEntrySelectionListBox()
{
//Fill listBox with entries for active user
DataContext = this;
entryItems = new ObservableCollection<ComboBoxItem>();
foreach (HistoryEntry h in activeUser.History)
{
var cbItem = new ComboBoxItem();
cbItem.Content = h.toString();
entryItems.Add(cbItem);
}
this.entrySelection.ItemsSource = entryItems;
labelEntrySelection.Text = "Einträge für: " + activeUser.Id;
//show image matching the selected entry
if (activeUser.History != null)
{
int index = entrySelection.SelectedIndex;
if (index != -1 && index < activeUser.History.Count)
{
this.entryImage.Source = activeUser.History[index].Image;
}
}
}
So I can see my ListBox correctly filled, but not select anything - so I can't go on with loading the picture matching the selected entry.
I'm still quite new to programming, so any help would be great :)
EDIT: If someone takes a look at this thread later: here's the - quite obvious -solution
XAML now looks like this
<ListBox x:Name="entrySelection" ItemsSource="{Binding Path=entryItems}" HorizontalAlignment="Left" Height="335" Margin="428,349,0,0" VerticalAlignment="Top" Width="540" FontFamily="Siemens sans" FontSize="24">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Text}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Code behind to fill it:
//Fill listbox with entries for selected user
DataContext = this;
entryItems = new ObservableCollection<DataItem>();
foreach (HistoryEntry h in selectedUser.History)
{
var lbItem = new DataItem(h.toString());
entryItems.Add(lbItem);
}
this.entrySelection.ItemsSource = entryItems;
labelEntrySelection.Text = "Einträge für: " + selectedUser.Id;
And new Class DataItem:
class DataItem
{
private String text;
public DataItem(String s)
{
text = s;
}
public String Text
{
get
{
return text;
}
}
}
You are filling it with ComboBoxItem, which is not relevant to the ListBox, and also wrong by definition.
You need to have the ObservableCollection filled with data items.
Meaning, make a class that contains the data you want to store, and the ListBox will generate a ListBoxItem automatically per data item.
http://www.wpf-tutorial.com/list-controls/listbox-control/
I want add Text to ListView element when i press button:
private void button_Click(object sender, RoutedEventArgs e)
{
listView.Items.Add(textBox.Text);
}
It works but i got:
Element1
Element2
Element3
But i want to see something like:
[]Element1
[]Element2
Where [ ] is checkbox :)
My xaml:
<ListView x:Name="listView" HorizontalAlignment="Left" Height="406" Margin="10,224,0,0" VerticalAlignment="Top" Width="340" />
I don't see option CheckBoxes True/False in my xaml Properties
XAML
Modify the listView item template to add your custom layout.
Add a data binding to the set the text
<ListView x:Name="listView" HorizontalAlignment="Left" VerticalAlignment="Stretch" Width="340">
<ListView.ItemTemplate>
<DataTemplate>
<WrapPanel>
<CheckBox/>
<Label Content="{Binding Text}"/>
</WrapPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Code Behind
declare this class somewhere
public class Row
{
private string text;
public Row (string text)
{
this.text = text;
}
public string Text
{
get { return text; }
set { text = value; }
}
}
Add this code to the constructor of the code associated with the xaml
ObservableCollection<Row> list = new ObservableCollection<Row>();
listView.ItemsSource = list;
How to add items/text to the listView
list.Add(new Row("Hello"));
list.Add(new Row("World"));
Hope this helps!
I want to use combo box and the following code is working but now I want to
add to the combo box header default value ,i.e. there is value and like
Item and when you open it you have the option to change it,how I can do that?
<ComboBox ItemsSource="{Binding Items}" SelectedValue="{Binding SelectedItem}"
Name="comboBox1" Text="Item" Grid.Column="3" Grid.Row="2" />
the code
private List<String> _items;
private String _selectedItem;
private String _selectedBusinessItem;
public List<String> Items
{
get { return _items; }
set
{
_items = value;
OnPropertyChanged("Items");
}
}
public String SelectedItem1
{
get { return _selectedItem; }
set
{
_selectedItem = value;
OnPropertyChanged("Items");
}
}
private void InitCombo()
{
Items = new List<string> { "item", "Item2", "Item3" };
SelectedItem1 = Items[0];
}
It's hard to understand you are asking, but I think you are just looking for the ComboBox to show the first value in the collection of Items.
I believe you can do this a few ways.
First you need to fix SelectedValue binding to match your property name, and drop the Text="Item":
<ComboBox ItemsSource="{Binding Items}" SelectedValue="{Binding SelectedItem1}"
Name="comboBox1" Grid.Column="3" Grid.Row="2" />
From your code you can set the SelectedValue1 property that you have to any of the string items. Examples of this:
SelectedValue1 = "item";
-or-
SelectedValue1 = Items.FirstOrDefault();
I used FirstOrDefault as a safety incase these items didn't exist.
-or-
SelectedValue1 = Items[0];
And there are several more options here. But I'm going to try and limit the scope of the answer.
Also, you should be able to set the ComboBox.SelectedIndex to 0.
<ComboBox ItemsSource="{Binding Items}" SelectedValue="{Binding SelectedItem1}"
Name="comboBox1" Grid.Column="3" Grid.Row="2"
SelectedIndex="0"/>
I think that you're talking about the ComboBox.Text Property... from the linked page:
Gets or sets the text of the currently selected item
This is not a free field that you can display a message in. It displays the value of the currently selected item from the ComboBox.Items collection. If the text is not in one of the items, then this TextBox 'should' not display that value.
However, there are always workarounds. The correct way to do it would be to define a new ControlTemplate for the ComboBox that contains a TextBlock that is overlayed on top of the selected item TextBox and hidden when required.
Some people think that that is too much work though and so you can find a number of alternative solutions in the How to display default text “--Select Team --” in combo box on pageload in WPF? post here on StackOverflow.
List Items = new List { "item", "Item 2", "Item 3" };
Set the Selected Index = 0, It will select the first element in the combo box Item-source
XAML:
<ComboBox ItemsSource="{Binding Items}"
Name="comboBox1" Grid.Column="3" Grid.Row="2"
SelectedIndex="0"/>
I have this ListBox:
<ListBox x:Name="PlaylistList" AlternationCount="2" SelectionChanged="DidChangeSelection">
<ListBox.GroupStyle>
<GroupStyle />
</ListBox.GroupStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And i want to add option to add new item to the ListBox. And i want to do it by adding a TextBox to the ListBox when the user press a Button and then the user press enter and add the text in the TextBox to the ListBox.
I try to add text box to the listbox but i can add only one type of ListBox.ItemTemplate, how can i handle it?
Updated to add textbox inside Listbox:
To add new item into ListBox, in Button Click code-behind do:
TextBox TextBoxItem = new TextBox();
// set TextBoxItem properties here
PlaylistList.Items.Add(TextBoxItem);
Your ListBox:
<ListBox
Name="MyListBox"
ItemsSource="{Binding Path=Reason}"
DisplayMemberPath="Description"/>
Make a ObversableCollection for the Items of the ListBox
public ObservableCollection<IdObject> items
{
get { return (ObservableCollection<IdObject>)GetValue(ApplicationsProperty); }
set { SetValue(ApplicationsProperty, value); }
}
items = new ObservableCollection<IdObject>();
My ID-Object in this case has the following properties:
private int _id = 0;
private string _description = "";
Bind the collection to the ListBox:
MyListBox.ItemsSource = items;
Then make a TextBox with a Button, and an event for pressing the button, where you add the text to the observable collection:
items.Add(new IdObject(someId, TextBox.Text));
The ListBox will update, when the ObservableCollection is changed
Write this code when your button is clicked so that the textbox text will be added to the listbox.
private void addEventButton_Click(object sender, EventArgs e)
{
// Adds events to listbox.
if (this.titleTextBox.Text != "")
{
listBox1.Items.Add(this.titleTextBox.Text);
listBox2.Items.Add(this.titleTextBox.Text);
this.titleTextBox.Focus();
this.titleTextBox.Clear();
}
}
I have a stored procedure called DropDownIndividuals() which was created using LINQ.
The stored procedure returns FullName and Case_Number. I want to set the SelectedValuePath equal to the Case_Number column in my stored procedure. This is how I did it for a listbox and it works.
private void listBox1_Loaded(object sender, RoutedEventArgs e){
using (ToolboxDataContext toolboxDB = new ToolboxDataContext())//this is linq in action
{
var x = toolboxDB.DropDownIndividuals().ToList();//convert to a list
listBox1.ItemsSource = x; //bind the data
listBox1.SelectedValuePath = "Case_Number";
listBox1.DisplayMemberPath = "FullName";
Console.WriteLine(listBox1.SelectedValue.ToString());
//Result:it shows the case number of the person the user picks.
}
}
Now I do the same thing for a dropdown combobox AND IT DOES NOT WORK.
private void individualDropDown_Loaded(object sender, RoutedEventArgs e)
{
using (ToolboxDataContext toolbox = new ToolboxDataContext())
{
var individualDropDownBox = toolbox.DropDownIndividuals().ToList();
individualDropDown.ItemsSource = individualDropDownBox;
individualDropDown.DisplayMemberPath = "FullName";
individualDropDown.SelectedValuePath = "Case_Number";
Console.WriteLine(individualDropDown.SelectedValue.ToString());
}
}
Why? How can I fix this?
Why so chaotic? You do not even set properties in the same order, this is equivalent:
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListBox Grid.Row="0" Grid.Column="0"
Name="lbData" ItemsSource="{Binding DpData}"
DisplayMemberPath="Name"
SelectedValuePath="Id"/>
<TextBlock Grid.Row="1" Grid.Column="0"
Text="{Binding ElementName=lbData, Path=SelectedValue}"/>
<ComboBox Grid.Row="0" Grid.Column="1" VerticalAlignment="Top"
Name="cbData" ItemsSource="{Binding DpData}"
DisplayMemberPath="Name"
SelectedValuePath="Id"/>
<TextBlock Grid.Row="1" Grid.Column="1"
Text="{Binding ElementName=cbData, Path=SelectedValue}"/>
</Grid>
...and it displays the same ID as expected.
Edit: At startup the selected value of both controls is null by the way.
You are correct, there is an inconsistency of sorts between the way that SelectedValue is treated for ListBox and ComboBox. For ListBox, upon load, if it has the focus, the SelectedValue will correspond to the first item in the data source. For ComboBox even if it has the focus and a data source supplies items, the default SelectedValue will be unset during the Loaded event handler.
This behavior is by design. To make the ComboBox behave like the ListBox set ComboBox.SelectedIndex to "0" where you define the ComboBox in the XAML.
Try this:
MetroAreaList metroAreaList = _presenter.GetMetroArea();
foreach (MetroArea metroArea in metroAreaList) {
lstMetroArea.DisplayMemberPath = "Name";
lstMetroArea.SelectedValuePath = "ID";
lstMetroArea.Items.Add(metroArea);
}
It is working....
Your class should be public:
public class Place
{
public string Name { get; set; }
public string Id { get; set; }
}
foreach (var y in Lists)
{
listBox1.DisplayMemberPath = "Name";
listBox1.SelectedValuePath = "Id";
// Console.WriteLine(y.Case_Number.ToString());
listBox1.Items.Add(y);
}