WPF binding TextBox and ObservableDictionary<Int64,String> (display String by Id) - wpf

Each item of my Employee's list has Post property. This property is Int64 type. Also, I have some ObservableDictionary<Int64,String> as static property. Each Employe must display the String value by its key.
DataTemplate for Employe item (I deleted the superfluous):
<DataTemplate x:Key="tmpEmploye">
<Border BorderThickness="3" BorderBrush="Gray" CornerRadius="5">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Path=Post}"/>
</StackPanel>
</Border>
</DataTemplate>
But this code displayed the Int64 value, not the String. String for getting static dictionary:
"{Binding Source={x:Static app:Program.Data}, Path=Posts}"
I know how solve it problem for ComboBox, but I don't know for TextBlock. For ComboBox I wrote it (it is works fine):
<ComboBox x:Name="cboPost" x:FieldModifier="public" Grid.Row="4" Grid.Column="1" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" Margin="2" Grid.ColumnSpan="2"
ItemsSource="{Binding Source={x:Static app:Program.Data}, Path=Posts}" DisplayMemberPath="Value"
SelectedValuePath="Key"
SelectedValue="{Binding Path=Post, Mode=TwoWay}">
</ComboBox>
But how can I solve it for TextBlock?

mmmmm, I'm sure I have developed something for this scenario before but I can't remember or find anything related!
IMO you can use a converter, so you pass your Post (Int64) to the converter and it returns the string value from the dictionary, although it must be a better solution.
[ValueConversion(typeof(Int64), typeof(string))]
public class PostToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// validation code, etc
return (from p in YourStaticDictionary where p.Key == Convert.ToInt64(value) select p.Value).FirstOrDefault();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
}
}
XAML:
<Window ...
xmlns:l="clr-namespace:YourConverterNamespace"
...>
<Window.Resources>
<l:PostToStringConverter x:Key="converter" />
</Window.Resources>
<Grid>
<TextBlock Text="{Binding Post, Converter={StaticResource converter}}" />
</Grid>
</Window>

Related

WPF MarkupExtension binding error

refers to implementing a multilanguage interface now I have a problem. I have a grid where its ItemSource it's a Dictionary<string, string>: I can't give the key value as parameter of the markup extension because I have the following exception
A 'Binding' cannot be set on the 'Value1' property of type 'TranslateMarkupExtension'.
A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
This is the xaml where I use the markup extension:
<ItemsControl ItemsSource="{Binding MyDictionary}" Grid.Row="0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Label Content="{TranslateMarkup Value1 = {Binding Path = Key}}" Grid.Column="0" />
<TextBox Tag="{Binding Key, Mode=OneWay}" Text="{Binding Value, Mode=OneWay}" Width="200" Height="46" VerticalContentAlignment="Center" Grid.Column="1" LostFocus="TextBox_OnLostFocus" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
I can't find any workaround..I need the dictionary as item source because the label will show the key and the textbox the corresponding value..I tried also replacing the dictionary with a list of object but the problem still remains.
Does anyone have a good hint? Thanks in advance.
As suggested by Ed Plunkett, the solution is the ValueConverter.
So the label is know this:
<Label Content="{Binding Key, Converter={StaticResource MultiLangConverter}}" Grid.Column="0" />
where my ValueConverter is the following:
public class StringToMultiLangConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var stringValue = (string) value;
if (string.IsNullOrEmpty(stringValue))
return string.Empty;
string multiLang = LangTranslator.GetString(stringValue);
return multiLang ?? value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
Thanks for the help!

WPF Combobox bind text

Maybe a simple task but I can't find the solution. I have a combobox connected to a database. Instead of displaying the content of ProductLookup I just want to display the words 'male' and 'female' on the popup menu.
Thank you
<ComboBox Height="23" Name="ComboBox2" Width="120" IsEditable="False"
ItemsSource="{Binding Source={StaticResource ProductLookup}}"
SelectedValue="{Binding Path=ProductID}"
SelectedValuePath="ProductID"
DisplayMemberPath="Name"/>
Write a Converter that takes one of your "Product" objects....looks at the gender related data inside it, or does the gender determining logic, and then returns the gender string, "male" or "female".
Then use it in your XAML to set the TextBlock:
<StackPanel Height="197" HorizontalAlignment="Left" Margin="300,6,0,0" Name="StackPanel5" VerticalAlignment="Top" Width="285"
DataContext="{Binding Source={StaticResource DetailViewPagos}}">
<StackPanel.Resources>
<local:ProductToGenderConverter x:Key="prodtogenderconv"/>
</StackPanel.Resources>
<ComboBox Height="23" Name="ComboBox2" Width="120" IsEditable="False"
ItemsSource="{Binding Source={StaticResource ProductLookup}}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource prodtogenderconv}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
public class ProductToGenderConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
MyProduct prod = value as MyProduct;
if (prod is for a male) // Pseudocode for condition
return "male";
if (prod is for a female) // Pseudocode for condition
return "female";
return null or "";
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
Alternatively you could provide a ViewModel which wraps your Product object, which has a specific property that indicates the "genderness" of the Product...then create a collection of those objects for setting in your ComboBox...then you can use DisplayMemberPath to point to that property.
Please see this answer, it is a way to wrap your values for nice binding and display in WPF.
The Item class could be modified to support object for the Code property.

Change DataTemplate to use depending on condition

I have 3 user controls
Control 1
Control 2
Control 3
I have a stack panel that contains an ItemsControl
<UserControl.Resources>
<DataTemplate x:Key="Template1">
<my:UserControl1 Height="117"/>
</DataTemplate>
<DataTemplate x:Key="Template2">
<my:UserControl3 Height="117"/>
</DataTemplate>
<DataTemplate x:Key="Template3">
<my:UserControl3 Height="117"/>
</DataTemplate>
</UserControl.Resources>
<StackPanel Name="stackPanel3" Orientation="Vertical" VerticalAlignment="Bottom" Width="Auto">
<ItemsControl ItemsSource="{Binding BlocksForMonth.Blocks}" ItemTemplate="{StaticResource Template1}">
</ItemsControl>
</StackPanel>
BlocksForMonths.Blocks is a list of view models. The Blocks class has a property called ClipType. If the clipType is 1, I want to use Template1. If its 2 I want to use Template 2. If its 3 I want to use Template 3
These templates contain different user controls
How can I do this through binding?
I have considered 1 template with the 3 controls, but I dont know how to bind the visibility?
In this XAML I am binding to a list not a single item
Paul
I would put the 3 controls in the same template and use Visibility to display the correct one. What I would do is build an IValueConverter to convert the deciding value (your case it's ClipType) and compare that to the ConverterParameter. If they are equal, return Visibility.Visible, otherwise return Visibility.Collapsed.
<UserControl.Resources>
<my:ClipTypeToVisibilityConverter x:Key="converter"/>
<DataTemplate x:Key="Template">
<StackPanel>
<my:UserControl1 Height="117" Visibility={Binding ClipType, Converter={StaticResource converter}, ConverterParameter=1} />
<my:UserControl2 Height="117" Visibility={Binding ClipType, Converter={StaticResource converter}, ConverterParameter=2} />
<my:UserControl3 Height="117" Visibility={Binding ClipType, Converter={StaticResource converter}, ConverterParameter=3} />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<StackPanel Name="stackPanel3" Orientation="Vertical" VerticalAlignment="Bottom" Width="Auto">
<ItemsControl ItemsSource="{Binding BlocksForMonth.Blocks}" ItemTemplate="{StaticResource Template}">
</ItemsControl>
</StackPanel>
This example assumes the ClipType property is on each item view model in the list being displayed.
Here is a C# example converter.
public class ClipTypeToVisibilityConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var clipType = value.ToString();
if (clipType == (string)parameter))
return Visibility.Visible;
return Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Sorry, everything was air-code. But I think you get the idea.

How do I Bind 2 controls to 1 field AND also access the 2 control values for ConvertBack?

In a DataGridTemplateColumn DataTemplate,
I want to bind 2 controls to a string field of format "[name]:[value]" i.e. the string is delimited by colon ":". I need to bind control a) to the [name] part and control b) the value part.
I have been able to successfully use an IValueConverter to split the string for display:
public class NameAndValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string rtn = "";
string[] split = value.ToString().Split(':');
if (split.Count() == 2)
{
if(parameter.ToString() == "Name")
rtn = split[0];
if(parameter.ToString() == "Value")
rtn = split[1];
}
return rtn;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new InvalidOperationException("NameAndValueConverter can only be used OneWay.");
}
}
And the XAML:
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<local:NameAndValueConverter x:Key="NameAndValueConverter" />
</StackPanel.Resources>
<TextBox x:Name="namePart" Text="{Binding Path=FieldType, Converter={StaticResource NameAndValueConverter}, ConverterParameter='Name'}" />
<TextBox x:Name="valuePart" Text="{Binding Path=FieldType, Converter={StaticResource NameAndValueConverter}, ConverterParameter='Value'}" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
But the data may be edited in the Textboxes so how can I access the 2 TextBox values in ConvertBack so that they can be joined again?
Doing this in the XAML:
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<local:NameAndValueConverter x:Key="NameAndValueConverter" />
</StackPanel.Resources>
<TextBox x:Name="namePart" Text="{Binding Path=FieldType, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource NameAndValueConverter}, ConverterParameter='Name'}" />
<TextBox x:Name="valuePart" Text="{Binding Path=FieldType, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource NameAndValueConverter}, ConverterParameter='Value'}" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
should be enough. You need a TwoWay binding to edit from UI, and when you set UpdateSourceTrigger to PropertyChanged the TextBox will update itself automatically when the property will be modified in the ViewModel (you'd obviously need to implement INotifyPropertyChanged )

WPF pass parent binding object to the converter

I have ItemsControl that is bound to collection of type Student.
Inside the ItemTemplate I have a TextBox that uses IValueConverter to do some custom calculations and logic. I want to pass the actual Student object to the value converter, instead a property of it. How can I do that? Here's a sample of my code.
<ItemsControl ItemsSource="{Binding StudentList}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding ????, Converter={StaticResource MyConverter}}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
In the code I have this
public class MyValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
// I want 'value' to be of type Student.
return null;
}
}
You can just leave out the path. That way you get at the actual object bound to.
<TextBlock Text="{Binding Converter={StaticResource MyConverter}}"/>
or if you want to be explicit about it:
<TextBlock Text="{Binding Path=., Converter={StaticResource MyConverter}}"/>

Resources