I have a listbox which stores records of XML file. My XMLfile has multiple elements like Name, Destination, employee ID. The listbox would display all the name contents of the XMLfile.
<Information>
<Name>Goutham</Name>
<Destination>dar</Destination>
<EmployeeID>da</EmployeeID>
</Information>
<Information>
<Name>Adam</Name>
<Destination>ads</Destination>
<EmployeeID>dwa</EmployeeID>
</Information>
<Information>
<Name>dwad</Name>
<Destination>wadwa</Destination>
<EmployeeID>daw</EmployeeID>
</Information>
The listbox displays all the different names like Goutham,Adam,dwad.
Now if I select Goutham in the listbox, I need to display all the details of Goutham on the textbox. How do i do it?
This is my xaml file
<ListBox Height="251" HorizontalAlignment="Left" Margin="330,23,0,0" Name="listBox1" VerticalAlignment="Top" Width="170" IsSynchronizedWithCurrentItem="True" DisplayMemberPath="Name" ItemsSource="{Binding}"/>
<TextBox Height="23" HorizontalAlignment="Left" Margin="141,42,0,0" Name="textBox1" VerticalAlignment="Top" Width="173" Text="{Binding ElementName= listbox1, Path=SelectedItem.Name}"/>
If the listbox fills up it should allready work, you just have a typo in the ElementName binding it should be listBox1.
Also if you want all the details not just the Name you could make a converter and leave only SelectedItem in the binding path. The converter would then format the details form the Information instance returning a string to be displayed in the texbox, or just use several textboxes.
Another option is to have MultiBinding with StringFormat:
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{0} {1} {2}">
<Binding ElementName="listbox1", Path="SelectedItem.Name" />
<Binding ElementName="listbox1", Path="SelectedItem.Destination" />
<Binding ElementName="listbox1", Path="SelectedItem.EmployeeID" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
You can bind ListBox to once specific property say Name & then bind TextBlock to this listbox. Depending upon your need, you can have individual TextBlocks for each property or a single TextBlock... as shown below...
<Window x:Class="ListBoxDataBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:ListBoxDataBinding"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<c:EmployeeConverter x:Key="myEmployeeConverter"/>
</Window.Resources>
<StackPanel Orientation="Vertical">
<ListBox x:Name="lbEmployee">
<ListBox.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Width="248" Height="24" Text="Employee Name" />
<TextBlock Grid.Row="0" Grid.Column="1" Width="248" Height="24" Text="{Binding ElementName=lbEmployee, Path=SelectedItem.Name}" />
<TextBlock Grid.Row="1" Grid.Column="0" Width="248" Height="24" Text="Employee EmployeeId" />
<TextBlock Grid.Row="1" Grid.Column="1" Width="248" Height="24" Text="{Binding ElementName=lbEmployee, Path=SelectedItem.EmployeeId}" />
<TextBlock Grid.Row="2" Grid.Column="0" Width="248" Height="24" Text="Employee Destination" />
<TextBlock Grid.Row="2" Grid.Column="2" Width="248" Height="24" Text="{Binding ElementName=lbEmployee, Path=SelectedItem.Destination}" />
<TextBlock Grid.Row="3" Grid.Column="0" Width="248" Height="24" Text="Employee Details" />
<TextBlock Grid.Row="3" Grid.Column="2" Width="248" Height="24">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource myEmployeeConverter}" ConverterParameter="FormatEmployee">
<Binding ElementName="lbEmployee" Path="SelectedItem.Name" />
<Binding ElementName="lbEmployee" Path="SelectedItem.EmployeeId" />
<Binding ElementName="lbEmployee" Path="SelectedItem.Destination" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Grid>
</StackPanel>
Code behind....
public partial class MainWindow : Window
{
private List<Employee> _lstEmployees;
public MainWindow()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
_lstEmployees = new List<Employee>();
_lstEmployees.Add(new Employee { Name = "Goutham", EmployeeId = "da", Destination = "dar" });
_lstEmployees.Add(new Employee { Name = "Adam", EmployeeId = "dwa", Destination = "ads" });
_lstEmployees.Add(new Employee { Name = "dwad", EmployeeId = "daw", Destination = "wadwa" });
lbEmployee.ItemsSource = _lstEmployees;
}
}
public class EmployeeConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
string name;
switch ((string)parameter)
{
case "FormatEmployee":
if (values[0] is String)
{
name = values[0] + ", " + values[1] + ", " + values[2];
}
else
{
name = String.Empty;
}
break;
default:
name = String.Empty;
break;
}
return name;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
string[] splitValues = ((string)value).Split(' ');
return splitValues;
}
}
Related
I have no idea how to achieve this, but I have a date and time column in a ListBox. The Date column should not display if the date was already in there. I know that in combination with ListCollectionView and Listview/DataGrids, it is propably possible. But can I achieve this with a ListBox and a List. Keep in mind I am using the MVVM principle. This is my listbox:
<ListBox Grid.Row="2" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ItemsSource="{Binding Schedules}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Background="Transparent">
<Grid Background="Transparent">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Text="{Binding MyDateTime, StringFormat='d' }" HorizontalAlignment="Left" VerticalAlignment="Center"/>
<TextBlock Grid.Column="1" Grid.Row="0" Text="{Binding MyDateTime, StringFormat='t'}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
<TextBlock Grid.Column="2" Grid.Row="0" Text="{Binding SomeText}" TextTrimming="WordEllipsis" LineStackingStrategy="MaxHeight" MaxHeight="20" HorizontalAlignment="Left" VerticalAlignment="Center"/>
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I have made this in excel to give an example of what I am trying to achieve:
I want the affect where I have highlighted with yellow
Converters
// Order Schedules using System.Linq
public class ToOrderedListConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
List<ScheduleItem> schedules = (List<ScheduleItem>)value;
var subset = from item in schedules
orderby item.MyDateTime.TimeOfDay
orderby item.MyDateTime.ToString("yyyy/MM/dd") descending
select item;
return subset.ToList();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
// Show only first occurrence of date
public class DateToVisibilityConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
DateTime currentItem = (DateTime)values[0];
List<ScheduleItem> schedules = (List<ScheduleItem>)values[1];
ScheduleItem firstOccurrence =
schedules.Find(item => item.MyDateTime.Year == currentItem.Year
&& item.MyDateTime.Month == currentItem.Month
&& item.MyDateTime.Day == currentItem.Day);
if (firstOccurrence.MyDateTime == currentItem)
return Visibility.Visible;
else return Visibility.Collapsed;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
XAML
<ListBox Grid.Row="2" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ItemsSource="{Binding Schedules, Converter={StaticResource ToOrderedListConverter}}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Background="Transparent">
<Grid Background="Transparent">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Text="{Binding MyDateTime, StringFormat='dd/MM/yyyy'}" HorizontalAlignment="Left" VerticalAlignment="Center">
<TextBlock.Visibility>
<MultiBinding Converter="{StaticResource DateToVisibilityConverter}">
<Binding Path="MyDateTime"/>
<Binding RelativeSource="{RelativeSource AncestorType={x:Type ListBox}}"
Path="ItemsSource"/>
</MultiBinding>
</TextBlock.Visibility>
</TextBlock>
<TextBlock Grid.Column="1" Grid.Row="0" Text="{Binding MyDateTime, StringFormat='t'}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
<TextBlock Grid.Column="2" Grid.Row="0" Text="{Binding SomeText}" TextTrimming="WordEllipsis" LineStackingStrategy="MaxHeight" MaxHeight="20" HorizontalAlignment="Left" VerticalAlignment="Center"/>
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
You can use this approach for your requirements.
https://code.msdn.microsoft.com/windowsdesktop/CollectionView-Tips-MVVM-d6ebb4a7#content
I have a list box bound to an observable object in my ViewModel. When the user selects an item in the listbox the SelectedItem fires the "SelectedSandwich" property. The value is saved to a private field. The properties SandwichName and Description are properties of the Sandwich object. I want text blocks in my view to show selected sandwichname and price, but I don't want to bind these text blocks to the listbox element.
Here is the view:
'
<Window.DataContext>
<vm:SandwichVM/>
</Window.DataContext>
<Window.Resources>
<DataTemplate x:Key="lstSandwich">
<Border BorderThickness="3"
CornerRadius="4"
HorizontalAlignment="Stretch"
BorderBrush="Blue">
<TextBlock HorizontalAlignment="Stretch">
<Run Text="{Binding SandwichName}"/>
<Run Text=" | " />
<Run Text="{Binding Description}" />
<Run Text=" | " />
<Run Text="{Binding Price}" />
</TextBlock>
</Border>
</DataTemplate>
<DataTemplate x:Key="menu" >
<Border>
<TextBlock HorizontalAlignment="Stretch">
<Run Text="{Binding SandwichName}"/>
<Run Text="{Binding Price}" />
</TextBlock>
</Border>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="2*"/>
</Grid.RowDefinitions>
<ListBox Grid.Row="0" x:Name="cboMenu"
ItemsSource="{Binding Sandwiches}"
SelectedItem="{Binding SelectedSandwich, Mode=TwoWay}"
ItemTemplate="{StaticResource lstSandwich}"
Margin="3">
</ListBox>
<Grid Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="3*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontStretch="ExtraExpanded"
FontFamily="Verdana"
FontSize="22"
>
<Run Text="Your Selection"/>
</TextBlock>
<Grid Grid.Row="1">
<ContentControl
ContentTemplate="{StaticResource menu}"
HorizontalAlignment="Stretch"
Margin="5,0,5,0">
</ContentControl>
</Grid>
</Grid>
</Grid>
</Window>'
Here is the ViewModel:
'class SandwichVM : INotifyPropertyChanged
{
private Sandwich _selectedSandwich;
private ObservableCollection<Sandwich> _sandwiches;
public ObservableCollection<Sandwich> Sandwiches
{
get { return _sandwiches; }
}
public SandwichVM()
{
//fake data for the list
_sandwiches = new ObservableCollection<Sandwich>();
_sandwiches.Add(new Sandwich("Pastrami", "Stacked high on rye bread with a touch of mustard.", 8.50));
_sandwiches.Add(new Sandwich("Tuna", "Fresh tuna salad on wheat with slice of cheddar cheese.", 6.50));
_sandwiches.Add(new Sandwich("Steak", "Sliced grilled steak with sauteed mushrooms and onions.", 9.50));
_sandwiches.Add(new Sandwich("Chicken Salad", "Juicy chunks of chicken breast, onions, fruit.", 6.50));
_sandwiches.Add(new Sandwich("Buffalo Chicken", "Caliente! Fried chicken breast slathered with hot buffalo wing sauce.", 8.50));
_sandwiches.Add(new Sandwich("Tofu", "I don't know how to make a tofu sandwich.", 1.50));
}
public Sandwich SelectedSandwich
{
get { return _selectedSandwich; }
set
{
if (_selectedSandwich != value)
{
_selectedSandwich = value;
RaisePropertyChangedEvent("SelectedSandwich");
}
}
}
public string SandwichName
{
get { return _selectedSandwich.SandwichName; }
set
{
_selectedSandwich.SandwichName = value;
RaisePropertyChangedEvent("SandwichName");
}
}
public string Description
{
get { return _selectedSandwich.Description; }
set
{
_selectedSandwich.Description = value;
RaisePropertyChangedEvent("Description");
}
}
public string Price
{
get { return _selectedSandwich.Price.ToString(); }
set
{
_selectedSandwich.Price = Convert.ToDouble(value);
RaisePropertyChangedEvent("Price");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChangedEvent(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}'
I tried putting the RaisePropertyChangedEvent in the setters for the three properties (though I only need to read them) but the setters are never executed. In fact, the setter for the SelectedSandwich property is never executed. The get is executed everytime. I have stepped through the code but can't see where the problem lies.
Thank you for your help.
Maybe its not clear to me, but the only property you are setting from UI is the SelectedSandwich property. If it sets properly when you change the selected listbox item then why not to bind to the SelectedSandwich from the other place?
So if you want some text blocks in your view to show selected sandwichname and price just try something like:
<TextBlock Text="{Binding SelectedSandwich.Name}"/>
<TextBlock Text="{Binding SelectedSandwich.Price}"/>
Or if you want to use your prepared datatemplate:
<DataTemplate DataType="{x:Type sandwichVMNamespace:Sandwich}">
<Border>
<TextBlock HorizontalAlignment="Stretch">
<Run Text="{Binding SandwichName}"/>
<Run Text="{Binding Price}" />
</TextBlock>
</Border>
</DataTemplate>
<Grid Grid.Row="1">
<ContentControl
Content="{Binding SelectedSandwich}"
HorizontalAlignment="Stretch"
Margin="5,0,5,0">
</ContentControl>
</Grid>
And you are done...
I have a ListBox with Questions and Answers which is taking data from Database. Now i want to display or edit data from selected row from 'Listbox', but i have problem how to get to this row.
Edit. Image to show what i want to do:
http://imgur.com/5NHjYA4
My View:
<Window x:Class="QuizMaker.MainWindow"
<Window.DataContext>
<local:MainViewModel />
</Window.DataContext>
<Window.Resources>
<DataTemplate x:Key="QuestionsTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="320" />
<ColumnDefinition Width="120" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="20" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Path=Question}" FontWeight="Bold" />
<TextBlock Grid.Column="1" Text="{Binding Path=AnswerA}" />
<TextBlock Grid.Column="2" Text="{Binding Path=AnswerB}"/>
<TextBlock Grid.Column="3" Text="{Binding Path=AnswerC}"/>
<TextBlock Grid.Column="4" Text="{Binding Path=AnswerD}"/>
<TextBlock Grid.Column="5" Text="{Binding Path=RightAnswer}" FontWeight="Bold"/>
</Grid>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox DataContext="{Binding MyDataSet}"
x:Name="listBox"
ItemsSource="{Binding Path=QuestionTable}"
ItemTemplate="{StaticResource QuestionsTemplate}"
SelectedItem="{Binding SelectedItemString}"
/>
</Grid>
</Window>
And ViewModel(I cut most of properties)
{
class MainViewModel
{
private string _appPath;
private MainModel _MainModel;
public MainViewModel()
{
_MainModel = new MainModel();
mdbFile = Path.Combine(AppDataPath, "QuestionBase.mdb");
connString = $"Provider=Microsoft.Jet.OLEDB.4.0; Data Source={mdbFile}";
conn = new OleDbConnection(connString);
adapter = new OleDbDataAdapter("SELECT * FROM QuestionTable;", conn);
MyDataSet = new DataSet();
adapter.Fill(MyDataSet, "QuestionTable");
}
private void AddToDB()
{
conn.Open();
OleDbCommand myCommand = new OleDbCommand("Insert INTO QuestionTable ( Question, AnswerA, AnswerB, AnswerC, AnswerD ) Values(#Question, #AnswerA, #AnswerB, #AnswerC, #AnswerD)", conn);
myCommand.Parameters.Add("#Question", OleDbType.BSTR).Value = Question;
myCommand.Parameters.Add("#Question", OleDbType.BSTR).Value = AnswerA;
myCommand.Parameters.Add("#Question", OleDbType.BSTR).Value = AnswerB;
myCommand.Parameters.Add("#Question", OleDbType.BSTR).Value = AnswerC;
myCommand.Parameters.Add("#Question", OleDbType.BSTR).Value = AnswerD;
myCommand.ExecuteNonQuery();
conn.Close();
}
private string AppDataPath
{
get
{
if (string.IsNullOrEmpty(_appPath))
{
_appPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
}
return _appPath;
}
}
public OleDbDataAdapter adapter
{
get
{
return _MainModel.adapter;
}
set
{
_MainModel.adapter = value;
OnPropertyChanged("adapter");
}
}
public DataSet MyDataSet
{
get
{
return _MainModel.MyDataSet;
}
set
{
_MainModel.MyDataSet = value;
OnPropertyChanged("MyDataSet");
}
}
public string SelectedItemString
{
get
{
return _MainModel.SelectedItemString;
}
set
{
_MainModel.SelectedItemString = value;
OnPropertyChanged("SelectedItemString");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
Sorry I couldn't add a comment. I hope your requirement is to show the selected item's value in the TextBox and update the same value into your collection(in your case DataTable) as you change value from the TextBox. If that is your requirement change your TextBox bindings like this
<TextBox x:Name="ValueText" Text="{Binding SelectedItem.ColumnName, ElementName=listBox, UpdateSourceTrigger=PropertyChanged}" />
I don't know why you are binding SelectedItem to string type SelectedItemString property. It will create binding error as per your source.
Change your SelectedItemString property to a DataRow, and bind your other controls to that.
For example,
public DataRow SelectedItem
{
get
{
return _MainModel.SelectedItem;
}
set
{
_MainModel.SelectedItem = value;
OnPropertyChanged("SelectedItem");
}
}
And in XAML should be something like this :
<Window x:Class="QuizMaker.MainWindow"
<Window.DataContext>
<local:MainViewModel />
</Window.DataContext>
<Window.Resources>
<DataTemplate x:Key="QuestionsTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="320" />
<ColumnDefinition Width="120" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="20" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Path=Question}" FontWeight="Bold" />
<TextBlock Grid.Column="1" Text="{Binding Path=AnswerA}" />
<TextBlock Grid.Column="2" Text="{Binding Path=AnswerB}"/>
<TextBlock Grid.Column="3" Text="{Binding Path=AnswerC}"/>
<TextBlock Grid.Column="4" Text="{Binding Path=AnswerD}"/>
<TextBlock Grid.Column="5" Text="{Binding Path=RightAnswer}" FontWeight="Bold"/>
</Grid>
</DataTemplate>
</Window.Resources>
<DockPanel>
<ContentControl Content="{Binding SelectedItem}"
ContentTemplate="{StaticResource QuestionsTemplate}"
DockPanel.Dock="Top" />
<ListBox DataContext="{Binding MyDataSet}"
x:Name="listBox"
ItemsSource="{Binding Path=QuestionTable}"
ItemTemplate="{StaticResource QuestionsTemplate}"
SelectedItem="{Binding SelectedItem}"
/>
</DockPanel>
</Window>
Also if you really don't want to change the way you track your selected item, you could also bind directly to listBox.SelectedItem like Davys said
<ContentControl Content="{Binding ElementName=listBox, Path=SelectedItem}"
ContentTemplate="{StaticResource QuestionsTemplate}"
DockPanel.Dock="Top" />
I am getting data in JSON and storing in List by
List<Product> rootObject = JsonConvert.DeserializeObject<List<Product>>(e.Result);
and after that, I am displaying data in ListBox by
productlist.ItemsSource = rootObject;
My xaml file:-
<ListBox Height="600" HorizontalAlignment="Left" Margin="5,91,0,0" Name="productlist" VerticalAlignment="Top" Width="441"
SelectionChanged="productlistselectionchanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<!-- <Image Source="{Binding Path=http://callme4.com/images/classifieds/ad_images/IMG_20130728_132750.jpg}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/> -->
<StackPanel Width="370">
<TextBlock Text="{Binding title}" Foreground="#FFC8AB14" FontSize="28" />
<TextBlock Text="{Binding city}" TextWrapping="Wrap" FontSize="24" />
<TextBlock Text="{Binding realdata}" TextWrapping="Wrap" FontSize="24" />
<TextBlock Text="{Binding gender}" TextWrapping="Wrap" FontSize="24" />
<TextBlock Text="{Binding age}" TextWrapping="Wrap" FontSize="24" />
<TextBlock Text="{Binding price}" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This is working fine.
But i have a condition in textblock.
if ( realdata == 1)
gender and age should be display and price should be hide.
else
price should be display. and Gender with age should be hide.
Please help me.
You can use Visibility property bound on realdata with Converter. So your .xaml file should look as you can you on the following code snippet:
<ListBox Height="600" HorizontalAlignment="Left" Margin="5,91,0,0" Name="productlist" VerticalAlignment="Top" Width="441"
SelectionChanged="productlistselectionchanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<!-- <Image Source="{Binding Path=http://callme4.com/images/classifieds/ad_images/IMG_20130728_132750.jpg}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/> -->
<StackPanel Width="370">
<TextBlock Text="{Binding title}" Foreground="#FFC8AB14" FontSize="28" />
<TextBlock Text="{Binding city}" TextWrapping="Wrap" FontSize="24" />
<TextBlock Text="{Binding realdata}" TextWrapping="Wrap" FontSize="24" />
<TextBlock Text="{Binding gender}" Visibility="{Binding readldata, Converter={StaticResource VisibilityConverter}}" TextWrapping="Wrap" FontSize="24" />
<TextBlock Text="{Binding age}" Visibility="{Binding readldata, Converter={StaticResource VisibilityConverter}}" TextWrapping="Wrap" FontSize="24" />
<TextBlock Text="{Binding price}" Visibility="{Binding readldata, Converter={StaticResource VisibilityConverter}}" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
In this case you have to create VisibilityConverter class:
public sealed class VisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int convertValue = (int)value;
if (convertValue == 1)
return Visibility.Collapsed;
else
return Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
And add this class to your application resources in app.xaml. First of all add namespace of your converter class to app.xaml:
xmlns:converters="clr-namespace:MyApplicationNameSpace"
and then add following line of code into your resources:
<converters:VisibilityConverter x:Key="VisibilityConverter" />
This solution not so short, but it helpful, when you use MVVM-pattern or just like to use data binding.
Take each item on your list and give condition.
try this one ..
foreach (Product currentProduct in rootObject ) // Loop through List with foreach
{
if(Product.realdata == 1) Price = "";
else {Gender =""; Age="";}
}
productlist.ItemsSource = rootObject;
For some reason using Content="{Binding Time, StringFormat=t} is still giving me a long date. The backing field is a DateTime property initialised with DateTime.Now but no matter what string format I try it still shows the full date...
I would like only to see HH:mm tt
Any ideas?
XAML :
<Window x:Class="ArgosSystem.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:ArgosSystem"
xmlns:sys="clr-namespace:System;assembly=System"
Title="MainWindow" Height="800" Width="1280" Loaded="Window_Loaded">
<Window.Resources>
<DataTemplate DataType="{x:Type loc:Picknote}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200" MinWidth="200" />
<ColumnDefinition Width="350" />
<ColumnDefinition Width="250" />
<ColumnDefinition Width="50" />
</Grid.ColumnDefinitions>
<Label Content="{Binding Time, StringFormat=t}" VerticalContentAlignment="Center" Foreground="IndianRed" FontSize="36" Grid.Column="0" />
<Label Content="{Binding Customer}" VerticalContentAlignment="Center" Foreground="IndianRed" FontSize="36" Grid.Column="1" />
<Label Content="{Binding PicknoteNo}" VerticalContentAlignment="Center" Foreground="IndianRed" FontSize="36" Grid.Column="2" />
<Label Content="{Binding Qty}" VerticalContentAlignment="Center" Foreground="IndianRed" FontSize="36" Grid.Column="3" />
</Grid>
</DataTemplate>
</Window.Resources>
<Grid Background="Black">
<DockPanel>
<ScrollViewer Name="lstPicknoteScroll" VerticalScrollBarVisibility="Auto">
<ItemsControl Name="lstPicknotes" ItemsSource="{Binding}" IsTabStop="False" Foreground="Cornsilk" />
</ScrollViewer>
</DockPanel>
</Grid>
</Window>
C# :
public partial class MainWindow : Window
{
ObservableCollection<Picknote> picknotes = new ObservableCollection<Picknote>();
public MainWindow()
{
InitializeComponent();
lstPicknotes.DataContext = picknotes;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
picknotes.Add(new Picknote
{
Time = DateTime.Now,
Customer = "REED FOR SPEED",
PicknoteNo = "PKN767677",
Qty = 100
});
picknotes.Add(new Picknote
{
Time = DateTime.Now.AddHours(-2),
Customer = "F1 AUTOMOTIVE",
PicknoteNo = "PKN767677",
Qty = 50
});
picknotes.Add(new Picknote
{
Time = DateTime.Now.AddHours(-1),
Customer = "FERGUSENS",
PicknoteNo = "PKN767677",
Qty = 10
});
}
}
StringFormat works on properties of type string. The Content property is of type Object so you need to specify the format using ContentStringFormat property of Label control.
<Label Content="{Binding Time}" ContentStringFormat="t" VerticalContentAlignment="Center" Foreground="IndianRed" FontSize="36" Grid.Column="0" />