Value converter change back to source - c#

I am using xml binding with my wpf controls, the XMLDocument is an exposed property of ViewModel. Here is the code:
public class ViewModel : ViewModelBase
{
private XmlDocument _xmlDataProvider;
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
base.RaisePropertyChangedEvent("Name");
}
}
public XmlDocument XmlDataProvider
{
get { return _xmlDataProvider; }
set
{
_xmlDataProvider = value;
base.RaisePropertyChangedEvent("XmlDataProvider");
}
}
}
And my XAML code Looks like this:
<UserControl x:Name="ctrlTemplate" x:Class= "CtrlTemplate"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WPFControl.UI"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:xckt="clr-namespace:Xceed.Wpf.Toolkit;assembly=Xceed.Wpf.Toolkit"
mc:Ignorable="d"
DataContext="{DynamicResource ViewModel}">
<UserControl.Resources>
<local:ViewModel x:Key="ViewModel" />
</ResourceDictionary>
</UserControl.Resources>
The following control is binded to a node in my xml:
<DatePicker DataContext="{Binding Path=XmlDataProvider}" SelectedDate="{Binding XPath=dataDocument/loan/paymentDates/paymentDate[1], Converter={StaticResource NullToDateConverter}, UpdateSourceTrigger=PropertyChanged}"/>
My converter in the code segment is as follows:
public class NullToDateConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (String.IsNullOrEmpty(value.ToString()))
{
return DateTime.Now.Date;
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value.ToString();
}
}
The converter works as intended, if the value of the node is empty. It sets the value of the datetime control to current value.
But I am facing the issue, that if the user for any reason does not change the value of datepicker and tries to save the xml, the value of the node in the xml remains null. What is the best way to do so?

WPF won't update the source if it doesn't think that the target's value is different from the source's. I.e. if the target value doesn't change.
You can, however, force WPF to update the source by calling the BindingExpression.UpdateSource() method. Without a good, minimal, complete code example that reliably reproduces the problem, it's impossible to say specifically how you'd incorporate this into your code. One obvious option would be to call it when the XML is to be saved (i.e. just before).
That might look something like this:
BindingOperations
.GetBindingExpression(datePicker1, DatePicker.SelectedDateProperty)
.UpdateSource();
That assumes, of course, that you name your DatePicker control as datePicker1.
This will ensure that whatever the current value of SelectedDate, it is copied back to the original source for the binding (i.e. the path in your XML).

Related

Is there a way to select the contents of COMBOBOX for copy/paste?

Problem: So my application has 2 options, load and update. When I want to update, I also want to copy the content (like Name/UID), but I can't. During update I set "isEnabled=False" (by binding it to a variable) it wont let me copy the content.
I tried doing "isReadOnly=True"(removing the "isEnabled" property), its allowing me to copy, but the DropDown is still working, which will allow me or anyone to change certain values,(like gender, UID) to change during update.
Goal: I want to be able to copy the content of the combobox but not letting anyone change its value.
OR
is there a way to disable the dropdown feature so that "isReadOnly=True" would do the trick.
If isReadOnly=True is doing what you want, then I will just use a converter to disable the dropdown.
In MainWindow.xaml:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1">
<Window.Resources>
<local:CBMaxDropDownHeightConverter x:Key="CBMaxDropDownHeightConverter" />
</Window.Resources>
<Grid>
<ComboBox MaxDropDownHeight="{Binding RelativeSource={RelativeSource Self}, Path=IsReadOnly, Converter={StaticResource CBMaxDropDownHeightConverter}}" />
</Grid>
</Window>
Then in CBMaxDropDownHeightConverter.cs
using System;
using System.Windows.Data;
namespace WpfApp1
{
public class CBMaxDropDownHeightConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (System.Convert.ToBoolean(value) == true)
{
return "0";
}
return "Auto";
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
}

WPF DataGrid display 'NULL' when bound property is null

I'm trying to display a cell containing a 'NULL' string instead of a blank cell when the corresponding source value is null. I'm using a DataGrid bound to a DataTable and AutoGenerateColumns="True".
Previously I managed to do it in the code-behind through the AutoGeneratedColumns event, but now I've switched to MVVM design and I wanted to avoid this.
foreach (var column in dgwCustomTableSelected.Columns)
{
if (column is DataGridTextColumn)
{
((DataGridTextColumn)column).Binding =
new Binding() {
Converter = new NullValueConverter((string)column.Header)
};
}
}
I was wondering whether there's a way to associate a Converter to all the datagrid columns or any other feasible solution to this.
Thanks in advance
I was wondering whether there's a way to associate a Converter to all the datagrid columns or any other feasible solution to this.
The "feasible solution" would be to handle the AutoGeneratingColumn event in the view. Or define all columns explicitly in the XAML markup of the same view.
Neither approach breaks the MVVM pattern since this is view-related functionality and MVVM is not about eliminating view-related code from the views. It is mainly about separation of concerns and doing view-related things programmatically instead of doing it in the XAML markup is perfectly fine.
I would try to do it in the ViewModel. Lets say your ViewModel class would look something like this (I left INotofyPropertyChanged out for simplicity):
public class ViewModel
{
private ModelClass model = new ModelClass();
public string Name
{
get
{
return model.Name;
}
set
{
model.name = value;
}
}
}
You could refactor it to something like this:
public class ViewModel
{
private ModelClass model = new ModelClass();
public string Name
{
get
{
if(model.Name == null)
{
return "NULL";
}
return model.Name;
}
set
{
model.name = value;
}
}
}
You could also try Custom Markup Extension that will allow you to include Converter inside of the Binding. For that to work you would also have to create DataTemplates for different types of data but overall gain, namely handling the data types, would outweigh the amount of coding. Here is an example of said Markup Extension from searchwindevelopment
class NumberToBrushConverter : MarkupExtension, IValueConverter
{
private static NumberToBrushConverter _converter = null;
public override object ProvideValue(IServiceProvider serviceProvider)
{
// determine if we have an instance of converter
// return converter to client
return _converter ?? (_converter = new NumberToBrushConverter());
}
public object Convert(object value, Type targetType,
object parameter,CultureInfo culture)
{
return new SolidColorBrush(Colors.Orange);
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Then in xaml you would use it like this:
<Window x:Class="ValueConverterTips.CustomMarkupTip"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:converters='clr-namespace:ValueConverterTips.Converters'
Title="CustomMarkupTip" >
<!-- no longer need the resources section -->
<Grid>
<Ellipse Fill='{Binding SomeIntData,
Converter={converters:NumberToBrushConverter}}'
Width='10' Height='10' />
</Grid>
</Window>
You would have to modify this to suit your scenario.
EDIT
This is how you would use this with AutoGenerateColumns=true:
<Style TargetType="DataGridColumnHeader">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Button Content="Ok"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<DataGrid AutGenerateColumns="true" ItemsSource={Binding xxx} etc...>
</DataGrid>

XAML - Display formatted ComboBoxItems

I have a WPF app. In this app, I have a ComboBox. The ComboBox display a list of algabra formulas. I want my students to be able to choose a formula. The formulas include superscripts. For that reason, I think I need to use a TextBlock like this:
<TextBlock>
<Run>x</Run>
<Run Typography.Variants="Superscript">2</Run>
<Run>+ 2xy </Run>
</TextBlock>
I am putting those formulas in
public class Formula
{
public string Text { get; set; }
public Formula(string text)
{
this.Text = text;
}
}
public class MyViewModel
{
public MyViewModel()
{
this.Formulas = new List<Formula>
{
new Formula("<TextBlock><Run>x</Run><Run Typography.Variants=\"Superscript\">2</Run><Run>+ 2xy </Run></TextBlock>"),
new Formula("<TextBlock><Run>x</Run><Run Typography.Variants=\"Superscript\">3</Run><Run>+ 3xy </Run></TextBlock>")
};
}
}
I am then trying to display those formulas, formatted, as ComboBoxItems. Currently, I have the following:
<ComboBox ItemsSource="{Binding Path=Formulas}" DisplayMemberPath="Text" />
This approach does not show the formulas formatted. Is there a way to bind ComboBoxItems to show formatted values? If so, how?
Thanks!
I would suggest to look into libraries that offer proper display of formulas (a similar answer here)
Although if you want to make this approach work you can do it the following way.
<Window x:Class="BindFormulas.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindFormulas"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:XamlTextToObjectConverter x:Key="XamlTextToObjectConverter" />
</Window.Resources>
<StackPanel>
<ComboBox ItemsSource="{Binding Path=Formulas}">
<ComboBox.ItemTemplate>
<DataTemplate DataType="local:Formula">
<ContentControl Content="{Binding Text, Converter={StaticResource XamlTextToObjectConverter}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
</Window>
The converter that will convert the XAML text to actual objects:
public class XamlTextToObjectConverter : IValueConverter
{
private static readonly Regex Regex = new Regex("(<.*?)>(.*)(</.*?>)", RegexOptions.Compiled);
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var xamlText = value as string;
if (xamlText != null)
{
var xamlTextWithNamespace = Regex.Replace(xamlText, "$1 xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">$2$3");
try
{
return XamlReader.Parse(xamlTextWithNamespace);
}
catch (Exception) // catch proper exceptions here, not just Exception
{
return value;
}
}
else
{
return value;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Again, probably you'd be better off with a library that does this properly :)
This approach is wrong for multiple reasons:
The Formula class probably shouldn't know about things like TextBlock and Run. That's not a model class's concern.
Also I'm sure you can provide a XAML string that will trip this converter up.
That said, if this will be a very simple app, where you will be a 100% sure that the XAML strings can be properly converted, then maybe this approach is OK as well.

Importing converter from dll into XAML

I have an EnumToBool Converter class in a dll file MicroMVVM. I want to import and create a resource of this class in XAML of my WPF application. Following is how my declaration in XAML looks like:
<Window x:Class="WpfMVVM.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:WpfMVVM"
xmlns:micro="clr-namespace:MicroMVVM;assembly=MicroMVVM"
Title="MainWindow" Height="350" Width="525" ContentRendered="Window_ContentRendered">
<Window.DataContext>
<!-- Declaratively create an instance of our SongViewModel -->
<local:SabrixQAViewModel />
</Window.DataContext>
<Window.Resources>
<micro:EnumToBoolExtension x:Key="EnumToBool" />
</Window.Resources>
I am getting error in "clr-namespace". The error is "Undefined CLR namespace.The 'clr-namespace' URI refers to a namespace 'MicroMVVM'that is not included in the assembly.
I have added a reference of MicroMVVM.dll in my solution and i am using other classes of the dll in the ViewModel. However, I am getting error while trying to use it in XAML. Please help.
Following is how the Converter class looks inside MicroMVVM:
namespace MicroMvvm
{
public enum ValidationMode
{
GSS,
Digital
}
[ValueConversion(typeof(bool), typeof(Enum))] //This is converting boolean value to a value in Enum
public class EnumToBoolExtension : MarkupExtension, IValueConverter
{
#region IValueConverter
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return parameter.Equals(value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((bool)value) == true ? parameter : DependencyProperty.UnsetValue;
}
#endregion
#region MarkupExtension
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
#endregion
}
}
Try to change this:
xmlns:micro="clr-namespace:MicroMVVM; assembly=MicroMVVM"
to:
xmlns:micro="clr-namespace:MicroMvvm;assembly=MicroMVVM"
There is a space between semicolon and the word assembly in your prefix declaration. That will make syntax wrong. Try to remove that space and try again.

Localizing dialogs in MVVM: is it good to reference the resources from the ViewModel?

I've gotten to the point where I need to add localization to my WPF MVVM application (I use Caliburn.Micro + Autofac).
I did some research, and I've found many different ways to accomplish it, but none provide a solution to localize the text of a dialog.
As dialogs I use a DialogViewModel that Caption and Message string properties, and I show it in a DialogView using CM's WindowManager.
What I have atm is something like
this.windowManager.ShowDialog(new DialogViewModel("Hello!", "Hello everybody!!"))
but also things like
this.windowManager.ShowDialog(new DialogViewModel("Hello!", "Hello " + this.Name + "!!"))
I thought I could use a resource string like "Hello {0}!!" and use it this way
this.windowManager.ShowDialog(new DialogViewModel("Hello!", string.Format(languageResources.HelloName, this.Name)))
Is it good to do reference the localization resources from the ViewModel layer?
Resources is the data that uses a View, and my opinion is that is not advisable from the ViewModel refer to resources. On the other hand, if it is a class (may be static) that stores a specific strings, and knows nothing of the View it will be some abstraction that can be in the ViewModel. In any case, you should try to work with the resources on the side View using techniques that I will give, or any other.
Using x:Static Member
In WPF, it is possible to bind static data from a class like this:
<x:Static Member="prefix : typeName . staticMemberName" .../>
Below is an example where the format string is in a class, the format used to display the date and time.
XAML
xmlns:local="clr-namespace:YourNameSpace"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
<Grid>
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}, StringFormat={x:Static Member=local:StringFormats.DateFormat}}"
HorizontalAlignment="Right" />
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}, StringFormat={x:Static Member=local:StringFormats.Time}}" />
</Grid>
Code behind
public class StringFormats
{
public static string DateFormat = "Date: {0:dddd}";
public static string Time = "Time: {0:HH:mm}";
}
In this case, the StringFormats class be regarded as a resource, although actually it is a normal class. For more information, please see x:Static Markup Extension on MSDN.
Using Converter
If you have the resources stored in Application.Current.Resources and need to add some logic, in this case, you can use the converter. This example is taken from here:
XAML
<Button Content="{Binding ResourceKey, Converter={StaticResource resourceConverter}}" />
Code behind
public class StaticResourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var resourceKey = (string)value;
// Here you can add logic
return Application.Current.Resources[resourceKey];
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new Exception("The method or operation is not implemented.");
}
}
Note: In the converter, it is better not to use heavy logic, because it can affect the performance. For more complex logic, see below.
Attached Behavior
Attached behavior should be used for complex actions with visual elements when no x:Static Member and converter is not helped. Attached behavior is very powerful and convenient solution that fully satisfies the MVVM pattern, which can also be used in the Blend (with a pre-defined interface). You can define an attached property in which property handler to access elements and to its resources.
Examples of implementation attached behaviors, see below:
Set focus to a usercontrol when it is made visible
Animated (Smooth) scrolling on ScrollViewer
Setting WindowStartupLocation from ResourceDictionary throws XamlParseException
Example with converter
App.xaml
Here I store strings for each culture.
<Application x:Class="MultiLangConverterHelp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
StartupUri="MainWindow.xaml">
<Application.Resources>
<sys:String x:Key="HelloStringEN">Hello in english!</sys:String>
<sys:String x:Key="HelloStringRU">Привет на русском!</sys:String>
</Application.Resources>
</Application>
MainWindow.xaml
The input is the current culture, which can be obtained within the converter, for simplicity of an example I did so.
<Window x:Class="MultiLangConverterHelp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MultiLangConverterHelp"
WindowStartupLocation="CenterScreen"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:StaticResourceConverter x:Key="converter" />
<local:TestViewModel x:Key="viewModel" />
</Window.Resources>
<Grid DataContext="{StaticResource viewModel}">
<TextBlock Text="{Binding Path=CurrentCulture, Converter={StaticResource converter}}" />
</Grid>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
public class StaticResourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var currentCulture = (string)value;
if (currentCulture.Equals("EN-en"))
{
return Application.Current.Resources["HelloStringEN"];
}
else if (currentCulture.Equals("RU-ru"))
{
return Application.Current.Resources["HelloStringRU"];
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
}
public class TestViewModel : NotificationObject
{
private string _currentCulture = "EN-en";
public string CurrentCulture
{
get
{
return _currentCulture;
}
set
{
_currentCulture = value;
NotifyPropertyChanged("CurrentCulture");
}
}
}
Also, I advise you to learn more simple ways, which is already in the WPF technology:
WPF Localization for Dummies
WPF Globalization and Localization Overview

Categories

Resources