I need to get attribute of listbox selecteditem wpf - c#

I have that listbox: my bind is ProdutoGrupoViewModel, and list named as ListBoxGrupos
<ListBox HorizontalAlignment="x:Name="ListBoxGrupos"
ItemsSource="{Binding ProdutoGrupoViewModel}"
SelectionChanged="ListBoxGrupos_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate x:Name="ListViewGrupos">
<StackPanel>
<TextBlock Text="{Binding Descricao}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
and when i get on my xaml.cs the property ListBoxGrupos.selectedItem, that returns for me an object
that object have some attributes
Obj.Descricao = "Pizzas"
Obj.GrupoCor = "FF8040"
Obj.GrupoID = 3
Obj.Image = "..."
Obj.Position = "0" ```
(i tried to upload the image of that obj, but need reputation, so i tried to explain)
i want to know how can i get the attribute GrupoID.

You need to cast the object to specified class
Grupo gru = (Grupo)ListBoxGrupos.SelectedItem;
gru.GrupoID = 3;

Related

How to change TextBlock Text Binding in C#

I'm working in huge application and I have one small problem
My Application has two languages (Arabic / English).
I have ComboBox And I would like to change the display content according to the language.
This is my ComboBox XAML:
<ComboBox x:Name="cmbCustomerGroup" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="5"
Margin="2" SelectedValuePath="CustomerGroupId" Validation.Error="Validation_Error"
SelectedValue="{Binding Path=CustomerGroupId, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True}">
<!--<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>-->
</ComboBox>
This is my method:
private void FillCustomerGroups()
{
var oClsCustomers = new ClsCustomerGroups();
var lstCustGrps = oClsCustomers.GetData();
cmbCustomerGroup.ItemsSource = lstCustGrps.ToList<TbCustomerGroups>();
cmbCustomerGroup.DisplayMemberPath = Helper.CurrLang == Helper.SystemLanguage.Arabic ? "CustomerGroupAName" : "CustomerGroupEName";
cmbCustomerGroup.SelectedValuePath = "CustomerGroupId";
}
I got this result:
This is my database:
This usually occurs when DisplayMemberPath is set wrong, or bindable property is not a string and has no overriden ToString() method.
Try add new property to your TbCustomerGroups, for example CurrentGroupName like this
public string CurrentGroupName => Helper.CurrLang == Helper.SystemLanguage.Arabic ? CustomerGroupAName : CustomerGroupEName;
Then set cmbCustomerGroup.DisplayMemberPath = "CurrentGroupName"
Also check that CustomerGroupAName and CustomerGroupEName are strings or have ToString() method
UPDATE
Also don't use <ComboBox.ItemTemplate> if you use DisplayMemberPath

Multi level data Binding in Windows Phone 8

I am a beginner in Windows phone programming.
I want to bind the data from API to my XAML elements using that Binding Attributes. Please let me know how can we bind multilevel classes objects in it.
Here's my scenario.
List<Sample> SearchResult = new List<Sample>()
{
new Sample(){
Name="ABC",
modelProperty = new SampleDetail(){
articleNo="1", videoURL = "https://www.youtube.com/watch?v=abc",
colors = new List<ColorsDemo>(){
new ColorsDemo {
Name = "Red",
colorProperty= new ColorDemoProperty{ name = "ABC",article_no = "Art1",
image = new Uri("http://img.youtube.com/vi/e60E99tUdxs/default.jpg",UriKind.RelativeOrAbsolute)
}
}
}
}
}
And now, I want to bind the Name of ColorsDemo class into my textblock. See what I have done to bind in XAML like this:
<TextBlock x:Name="PName" Grid.Row="0" Margin="100,0,0,0" Tap="ProductName_Tap" HorizontalAlignment="Center" VerticalAlignment="Center" Width="350" TextWrapping="Wrap" Foreground="Black" Text="{Binding Path=modelProperty.colors.Name}" FontSize="30"></TextBlock>
From your code, i see that colors is a List of ColorDemo objects. So when you say {Binding Path=modelProperty.colors.Name}it does not tell which list item to bind to. The correct usage should be {Binding Path=modelProperty.colors[0].Name}. This tells the control to bind to the name of the first color item (as index is 0).
To bind all the colors. You should use a Listview and bind the colors in it. So you should be able to do something like this.
<ListView ItemSource={Binding Path=modelProperty.colors}>
<ListView.ItemTemplate>
<TextBlock x:Name="PName" Grid.Row="0" Margin="100,0,0,0" Tap="ProductName_Tap" HorizontalAlignment="Center" VerticalAlignment="Center" Width="350" TextWrapping="Wrap" Foreground="Black" Text="{Binding Path=Name}" FontSize="30"></TextBlock>
</ListView.ItemTemplate>
</ListView>

WPF Binding: How to bind a name from a list of filepaths to text of TextBlock in ListBox?

i'm trying to bind a name of a file given by a filepath to a TextBlock. The filepath is stored in a list which is bound to the ItemsSourceProperty of a ListBox. The TextBlock is set as DataTemplate.
My question is: How can i get the name without path and extension and bind it to the TextBlock?
The XAML code for better explanation:
<ListBox Name="MyListBox" Margin="2">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And the code behind:
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
List<string> PathList = Directory.GetFiles(path, "*.txt").ToList();
Binding myBind = new Binding();
myBind.Source = PathList;
myListBox.SetBinding(ListBox.ItemsSourceProperty, myBind);
One uses a converter to change the text of a selected listbox item which is fully pathed to just the filename.
In the following example there is a list and a textbox next to it. Once an item is selected, the textbox bound to the list's SelectedItem extracts the pathed string which is passed to a converter which returns just the filename to show.
Example
XAML
<Window x:Class="WPFStack.ListBoxQuestions"
xmlns:local="clr-namespace:WPFStack"
xmlns:converters="clr-namespace:WPFStack.Converters"
.../>
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<converters:PathToFilenameConverter x:Key="FilenameConverter" />
<x:Array x:Key="FileNames" Type="system:String">
<system:String>C:\Temp\Alpha.txt</system:String>
<system:String>C:\Temp\Beta.txt</system:String>
</x:Array>
</StackPanel.Resources>
<ListBox Name="lbFiles"
ItemsSource="{StaticResource FileNames}" />
<TextBlock Text="{Binding SelectedItem,
ElementName=lbFiles,
Converter={StaticResource FilenameConverter}}"
Margin="6,0,0,0" />
</StackPanel>
Converter
namespace WPFStack.Converters
{
public class PathToFilenameConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
object result = null;
if (value != null)
{
var path = value.ToString();
if (string.IsNullOrWhiteSpace(path) == false)
result = Path.GetFileNameWithoutExtension(path);
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
}
ItemTemplate Use of Converter
The converter is reused in the template as such
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource FilenameConverter}}"/>
</DataTemplate>
</ListBox.ItemTemplate>
If you just want to add a static list to list box you should do it like this.
XAML:
<ListBox x:Name="lb" ItemsSource="{Binding Collection}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The code behind constructor for in the main window:
public MainWindow()
{
InitializeComponent();
List<string> l = new List<string>();
l.Add("string path 1");
l.Add("string path 2");
l.Add("string path 3");
l.Add("string path 4");
lb.ItemsSource = l;
}
You should be aware that there is a much better way of doing these things. I would honestly suggest you go look MVVM and doing a proper binding to a ViewModel.

ObservableCollection from Linq

Can someone see what I need to change here? I am displaying an observablecollection of AddressTypeClass items. The object items show up in the listbox instead of the data. I can see the data in the objects in debug mode.
THE XAML.CS FILE:
DataContext MyTableDataContext = new MyTableDataContext();
ObservableCollection<AddressTypeClass> theOC = new ObservableCollection<AddressTypeClass>(new MyTableDataContext().AddressTypes.AsEnumerable()
.Select(lt => new AddressTypeClass
{
AddressTypeID = lt.AddressTypeID,
AddressType = lt.AddressType,
})
.ToList());
this.listBox1.ItemsSource = theOC;
THE XAML FILE:
<ListBox Name="listBox1" Margin="8" Height ="200" Width ="150" FontSize="12" Foreground="#FF2F3806" ItemsSource="{Binding AddressType}" IsSynchronizedWithCurrentItem="True" >
</ListBox>
You need to add an ItemTemplate to your ListBox, e.g.
<ListBox Name="listBox1" Margin="8" Height ="200" Width ="150" FontSize="12" Foreground="#FF2F3806" ItemsSource="{Binding AddressType}" IsSynchronizedWithCurrentItem="True" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=AddressType}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
You can impove your code by using my ObservableComputations library. In your code you manualy update theOC every time MyTableDataContext.AddressTypes dbSet (I assume you are using EntityFramework) changes (new item or remove) or properties (AddressType.AddressTypeID, AddressType.AddressType) changes. Using AddressType you can automate that process:
DataContext MyTableDataContext = new MyTableDataContext();
ObservableCollection<AddressTypeClass> theOC = MyTableDataContext.AddressTypes.Local
.Selecting(lt => new AddressTypeClass
{
AddressTypeID = lt.AddressTypeID,
AddressType = lt.AddressType,
});
this.listBox1.ItemsSource = theOC;
theOC is ObservableCollection and reflects all the changes in the MyTableDataContext.AddressTypes.Local collection and properties mentioned in the code above. Ensure that all properties mentioned in the code above notify of changes through the INotifyProperytChanged interface.

Get selected item from a ListBox at hold

I've got a ListBox in a WP7 App where I want to do something with an item when the user hold it. The event work's great. My hold method gets called, but I can't detect which element in the list was hold.
ListBox.SelectedItem is always -1 and a code from another post on stackoverflow doens't work:
FrameWorkelement element = (FrameworkElement) e.OriginalSource;
ItemViewModel item = (ItemViewModel) element.DataContext;
I get an InvalidCastException when running it in the second line.
The following code should work.
private void StackPanel_Hold(object sender, GestureEventArgs e)
{
ItemViewModel itemViewModel = (sender as StackPanel).DataContext as ItemViewModel;
string t = itemViewModel.LineOne;
}
Note: before using the DataContext of the sender object, make sure you cast the sender object to the correct class. In this example I use a StackPanel in my DataTemplate:
<ListBox x:Name="MainListBox" Margin="0,0,-12,0" ItemsSource="{Binding Items}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Height="78" Hold="StackPanel_Hold">
<TextBlock Text="{Binding LineOne}" />
<TextBlock Text="{Binding LineTwo}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Categories