May be I missed something, but I've already beat my head with this one.
I have defined CollectionViewSource:
<CollectionViewSource x:Key="packagesViewSource" d:DesignSource="{d:DesignInstance my:Package, CreateList=True}" />
and ListBox:
<ListBox Name="lstbPackages"
SelectionChanged="lstbPackages_SelectionChanged"
ItemsSource="{Binding Source={StaticResource packagesViewSource}}"
DisplayMemberPath="Name"
SelectedValue="{Binding Path=PackageId, UpdateSourceTrigger=Explicit}"
SelectedItem="{Binding Path=Package}"
SelectedValuePath="IdPackage"
/>
Also, I have code-behind packagesViewSource initialization:
private IQueryable<Packages> GetPackagesQuery()
{
IQueryable<Package> query = dc.PackagesList;
// Returns an ObjectQuery.
return query;
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
...
packagesViewSource =((System.Windows.Data.CollectionViewSource)(this.FindResource("packagesViewSource")));
queryPackages = this.GetPackagesQuery();
packagesViewSource.Source = queryPackages.ToList();
...
}
And the line
packagesViewSource.Source = queryPackages.ToList();
involves event
private void lstbPackages_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
...
}
and as you could guess
lstbPackages.SelectedItem != null
there.
What I do wrong?
Try adding the following to your ListBox xaml.
IsSynchronizedWithCurrentItem="false"
when you assign a source to your ListBox, a DefaultView of your packagesViewSource CollectionViewSource is created. and it has first element selected. So when assigning the source, do it in 3 step:
Get DefaultView for your resource, then
MoveCurrentToPosition(-1) on this view, then
assign the View with correct current position to ListBox.
Related
I have a problem here to take the text from selected item inside of my ListPicker,i found this code who allows me to do that
var content = ((ListPickerItem)CursoLista.SelectedItem).Content;
and my XAML:
<toolkit:ListPicker x:Name="CursoLista" Header="Curso" ItemsSource="{Binding}">
<toolkit:ListPicker.ItemTemplate>
<DataTemplate>
<StackPanel>
<toolkit:ListPickerItem Content="{Binding Curso}"/>
</StackPanel>
</DataTemplate>
</toolkit:ListPicker.ItemTemplate>
</toolkit:ListPicker>
as you can see,the content is Binding to a List from my server:
private void Cliente_ProfessorRetrieveCompleted(object sender, Service.ProfessorRetrieveCompletedEventArgs e)
{
CursoLista.ItemsSource = e.Result;
but when i try to do this,i have an Execption :
Additional information: Unable to cast object of type 'FaculdadeGuararapes.Service.ListaProfessor' to type 'Microsoft.Phone.Controls.ListPickerItem'.
FaculdadeGuararapes.Service.ListaProfessor its the list who comes from my WebServer!
First of all, if your e.Result is a list of strings and you set CursoLista.ItemsSource from code behind, you don't need to add ItemsSource in xaml. Next, if you want to retreive single selected item, just pin to SelectionChanged event. Additionally, probably it's not necessary to add <DataTemplate>. DataTemplate is only necessary when you want to customize a layout or bind to the class.
<toolkit:ListPicker x:Name="CursoLista" Header="Curso" SelectionChanged="CursoLista_SelectionChanged">
</toolkit:ListPicker>
and handle it in code behind:
private void CursoLista_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string selectedString = (sender as ListPicker).SelectedItem as string;
}
I am trying to add new item in to Combobox .For ex : if the ComboBox itemssource having "one","two",and "three ". I am able to type by setting IsEditable property to true . New item "Four" which is need to save in combobox . Please share regarding this .
<Window.Resources>
<local:OrderInfoRepositiory x:Key="ordercollection"/>
</Window.Resources>
<ComboBox x:Name="combo" IsEditable="True" ItemsSource="{Binding ComboItems,Source={StaticResource ordercollection}}" Height="50" Width="150"/>
code behind :
void combo_PreviewKeyDown(object sender, KeyEventArgs e)
{
var combo=(sender as ComboBox);
(combo.DataContext as OrderInfoRepositiory).ComboItems.Add(combo.Text);
}
private ObservableCollection<string> comboItems = new ObservableCollection<string>();
public ObservableCollection<string> ComboItems
{
get { return comboItems; }
set
{
comboItems = value;
RaisePropertyChanged("ComboItems");
}
}
public OrderInfoRepositiory()
{
orderCollection = new ObservableCollection<OrderInfo>();
OrderInfoCollection = GenerateOrders();
foreach (OrderInfo o in orderCollection)
{
comboItems.Add(o.Country);
}
}
PreviewKeyDown
Your ComboBox is not bound to the EventHandler comboBox_PreviewKeyDown.
Are you really want to use PreviewKeyDown?
With PreviewKeyDown comboBox.Text still has the Text before excluding your pressed key. Use KeyDown instead.
Each Keypress will add the new and the old typed letters.
Typing "Hello World" will end in H, He, Hel, Hell, etc.
Check for Key.Return to add the Item on completion or use a button. Then you can still use the PreviewKeyDown Event.
void combo_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
var combo = (sender as ComboBox);
(combo.DataContext as OrderInfoRepository).ComboItems.Add(combo.Text);
}
}
DataContext
You are casting DataContext to OrderInfoRepositiory but there is no assignment in your code.
Add to your ComboBox:
DataContext="{Binding Source={StaticResource ordercollection}}"
Then you can change your ItemsSource:
ItemsSource="{Binding ComboItems}"
I prefer setting OrderInfoRepositiory in my underlying ViewModel, then you do not need the StaticResource and just bind to the property.
<ComboBox x:Name="combo" IsEditable="True" DataContext="{Binding Source={StaticResource ordercollection}}" ItemsSource="{Binding ComboItems}" Height="50" Width="150" KeyDown="combo_PreviewKeyDown"/>
I have a longlistselector like the below image. now I wanna get the text of the item user's tapped. I've searched a lot but no solution found ;(
pay attention to the image please to give a sample code
http://amiryari.persiangig.com/image/stackoverflow-question.jpg
1) Wire up the SelectionChanged event on the LongListSelector control:
<phone:LongListSelector ItemsSource="{Binding MyListItems}"
SelectionChanged="LongListSelector_SelectionChanged">
2) Retrieve the selected item from the AddedItems collection in the SelectionChangedEventArgs:
private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
{
var item = e.AddedItems[0];
}
}
3) If your item is an object, and the text is displayed through a property, then you would have access to the text through the property on your object:
MyListItemObject item = e.AddedItems[0] as MyListItemObject;
MessageBox.Show(item.FullName);
If your list is bound to a list of strings, then it would simply be the first item in the AddedItems collection:
string fullName = e.AddedItems[0].ToString();
MessageBox.Show(fullName);
You can always listen for the SelectionChanged event and obtain the string. There is another way if you are using a DataTemplate to style your items in the list. Declare Tapped event in DataTemplate like this:
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ContactImage}"/>
<TextBlock x:Name="NameTextBlock" Text="{Binding ContactName}" Tapped="NameTextBlock_Tapped"/>
</StackPanel>
</DataTemplate/>
Now in our code:
private void LongListSelector_SelectionChanged(object sender, BlahBlah e)
{
var tb = sender as Textblock;
string cName = tb.Text; //This is the string you wanted.
MessageBox.Show(cName);
}
I'm trying to initiate an action based on a selection in a ComboBox I created in WPF. I'm pretty new to WPF and C#. My ComboBox has
<ComboBox x:Name="SampleComboBox" Width="100" ItemsSource="{Binding Path=NameList}" />
Where NameList is a List property in the code behind. Now I want to generate an action based on the selection in the ComboBox and not sure where to start. Thanks.
You'll need to add a method to handle the SelectionChanged event. You can either do this in code:
this.MyComboBox.SelectionChanged += new SelectionChangedEventHandler(OnSelectionChanged);
or in XAML:
<ComboBox x:Name="SampleComboBox" Width="100"
ItemsSource="{Binding Path=NameList}" SelectionChanged="OnSelectionChanged" />
where you can then do something with the selected items:
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBoxItem cbi = (ComboBoxItem) (sender as ComboBox).SelectedItem;
}
You can get the selected object by writing SampleComboBox.SelectedItem.
This will return an instance of an item in your source list.
Are these a finite set of values in this NameList that is the ItemsSource for this?
Why not amend that xaml to read:
<ComboBox x:Name="SampleComboBox" Width="100" SelectedItem="{Binding TheItem}" ItemsSource="{Binding Path=NameList}" />
and then in your ViewModel for this, have something like:
public static readonly DependencyProperty TheItemProperty=
DependencyProperty.Register("TheItem", typeof(string), typeof(OrderEditorViewModel),
new PropertyMetadata((s, e) => {
switch (e.NewValue) {
case "SomeValue":
// Do something
break;
case "SomeOtherValue":
// Do another thing
break;
default:
// Some default action
break;
}
}));
public string TheItem{
get { return (string)GetValue(TheItemProperty); }
set { SetValue(TheItemProperty, value); }
}
You can do your actions based on the selection in that switch statement which will be invoked whenever the selection is changed.
I have a datagrid which consists of a checkbox and couple of columns.
When the customer clicks the checkbox I am firing grid selectionchanged event which displays some data from selectedrow to the label.
But I need that selected row data when I click a button as well.
Is there any good way to retrieve that?
Based on your comment you should try this then (the DataGrid is named dataGrid in XAML):
private void Button1_Click(object sender, RoutedEventArgs e)
{
// If the grid is populated via a collection binding the SelectedItem will
// not be a DataGridRow, but an item from the collection. You need to cast
// as necessary. (Of course this can be null if nothing is selected)
var row = (DataGridRow)dataGrid.SelectedItem;
}
Could use the Tag (Edit: If you use a CheckBoxColumn you can use the styles to do this, if you have trouble with that i could give an example):
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="Button1_Click"
Tag="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
private void Button1_Click(object sender, RoutedEventArgs e)
{
var button = (FrameworkElement)sender;
var row = (DataGridRow)button.Tag;
//...
}