Variable Image Source inside a Button Template - wpf

How can I transfer the Source attribute from a button template to an Image inside that template ?
This is how my XAML looks like:
<Page x:Class="TallShip.MainGallery"
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:TallShip"
mc:Ignorable="d"
d:DesignHeight="1080" d:DesignWidth="1920"
Title="MainGallery">
<Grid>
<ScrollViewer Height="958" HorizontalAlignment="Left" Margin="685,87,0,0" Name="GalleryRightScroller" VerticalAlignment="Top" Width="1159" PanningMode="VerticalOnly" VerticalScrollBarVisibility="Auto">
<Grid>
<Grid.Resources>
<ControlTemplate x:Key="GalleryObject">
<StackPanel Height="Auto" HorizontalAlignment="Left" Margin="{TemplateBinding Margin}" VerticalAlignment="Top" Width="500">
<Image Height="200" Stretch="None" Source="{TemplateBinding local:SourceHolder.Source}" Width="200" />
<Label Content="{TemplateBinding local:SourceHolder.Source}" Height="28" Name="label1" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" />
</StackPanel>
</ControlTemplate>
</Grid.Resources>
<Button Template="{StaticResource GalleryObject}" local:SourceHolder.Source="/TallShip;component/media/91gx2EQ.jpg" Name="object1" Margin="43,21,0,0"/>
<Button Template="{StaticResource GalleryObject}" local:SourceHolder.Source="/TallShip;component/media/91gx2EQ.jpg" Name="object2" Margin="43,280,0,0"/>
</Grid>
</ScrollViewer>
</Grid>
And this is the custom control class I've created to hold the Source property:
namespace TallShip {
public static class SourceHolder
{
public static readonly DependencyProperty SourceProperty = DependencyProperty.RegisterAttached("Source",
typeof(string), typeof(SourceHolder), new FrameworkPropertyMetadata(null));
public static string GetSource(UIElement element)
{
if (element == null)
throw new ArgumentNullException("element");
return (string)element.GetValue(SourceProperty);
}
public static void SetSource(UIElement element, string value)
{
if (element == null)
throw new ArgumentNullException("element");
element.SetValue(SourceProperty, value);
}
}
}
Currently, the label correctly displays the passed source, but the image does not work...
If I use the same source on an image outside of the button template, the image works just fine.

Option 1:
<Image Height="200" Stretch="None" DataContext="{TemplateBinding local:SourceHolder.Source}" Width="200" Source="{Binding}"></Image>
Option 2:
If that does not work, Use other alternative of using ValueConverter in Image binding that converts uri to Image
public class UriToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return null;
if (value is string)
value = new Uri((string)value, UriKind.RelativeOrAbsolute);
if (value is Uri)
{
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = (Uri)value;
bi.EndInit();
return bi;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
<Window.Resources>
<local:UriToImageConverter x:Key="uriToImageConverter"></local:UriToImageConverter>
</Window.Resources>
<Image Height="200" Stretch="None" DataContext="{TemplateBinding local:SourceHolder.Source}" Width="200" Source="{Binding Converter={StaticResource ResourceKey=uriToImageConverter}}"></Image>

Related

WPF EventHandler for TextBox.TextChanged in XAML or code behind?

Description
In WPF, using MvvmLight, I have a viewModel with an integer property SelectedIndex. Changing the value of this property is an expensive operation, so I only want to update the property if the operator is fairly certain that he finished typing.
I have a TextBox and a button. The operator types a number, and presses the button. This should lead to a command that updates the property.
Standard WPF MvvmLight solution for this
class MyViewModel
{
private int selectedIndex;
public MyViewModel()
{
this.CommandSelectIndex = new RelayCommand(ExecuteSelectIndex, CanSelectIndex);
}
public public RelayCommand<int> CommandSelectIndex { get; }
public int SelectedIndex
{
get => this.selectedIndex;
set => base.Set(nameof(SelectedIndex), ref this.selectedIndex, value);
}
private bool CanSelectIndex(int proposedIndex)
{
return proposedIndex > 0 && proposedIndex < MyData.Count;
}
private void ExecuteSelectIndex(int proposedIndex)
{
this.SelectedIndex = proposedIndex;
ProcessSelectedIndex(proposedIndex); // Expensive!
}
}
For those who know MvvmLight, this is fairly straightforward.
So while the operator is typing a number, I only want to update the button. I don't want to do anything with the intermediate values:
1 --> 12 --> 123 --> (typing error, backspace) --> 124 [press button]
XAML
<StackPanel Name="Test1" Orientation="Horizontal">
<TextBox Name="ProposedValue1" Text="1234" Width="300" Height="20"/>
<Button x:Name="ButtonChangeText1" Content="Change"
Height="30" Width="74" Padding="5,2"
Command="{Binding Path=CommandSelectedIndex}"
CommandParameter="{Binding ElementName=ProposedValue1, Path=Text}"/>
</StackPanel>
This works partly: at startup CanSelectIndex(1234) is called; If the button is pressed ExecuteSelectedIndex(1234) is called.
Problem
However, if the text of the TextBox changes, CanSelectIndex is not called.
The reason is because event ICommand.CanExecuteChanged is not raised when the textbox changes.
Solution:
Add an event handler:
XAML:
<TextBox Name="ProposedValue1" Text="1234" Width="300" Height="20"
TextChanged="textChangedEventHandler"/>
Code behind:
private void textChangedEventHandler(object sender, TextChangedEventArgs args)
{
((MyViewModel)this.DataContext).CommandSelectedIndex.RaiseCanExecuteChanged();
}
I always feel a bit uneasy whenever I have to write code behind. Is it standard to write eventhandlers in code behind, or is that a simplification that I only see in tutorials.
Is there a method that I can do this in XAML? Something with Binding?
TextChanged="TextChanged="{Binding Path=CommandSelectIndex ??? RaiseCanExecuteChanged() }
The RelayCommand class in MvvmLight has two implementations.
In the GalaSoft.MvvmLight.Command namespace and in the GalaSoft.MvvmLight.CommandWpf namespace.
You've probably used from namespace GalaSoft.MvvmLight.Command.
And this type doesn't actually update the state of the command.
If used from the GalaSoft.MvvmLight.CommandWpf namespace, then the state of the command is updated according to the predetermined logic.
Is there a method that I can do this in XAML? Something with Binding?
Just bind the Text property of the TextBox to a string source property of the view model and raise call the RaiseCanExecuteChanged method of the command from the setter of this one.
If you really want to handle an actual event for some reason, you should look into interaction triggers.
#Harald Coppulse, you are absolutely right!
Here is my test code for MvvmLight.
ViewModel:
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
namespace InvalidateCommandMvvmLight.ViewModel
{
public class MyViewModel : ViewModelBase
{
private string _text;
private int _number;
public string Text { get => _text; private set => Set(ref _text, value); }
public int Number { get => _number; set => Set(ref _number, value); }
public RelayCommand<string> CommandTest { get; }
public RelayCommand<int> CommandNumber { get; }
public MyViewModel()
{
CommandTest = new RelayCommand<string>(Test, CanTest);
CommandNumber = new RelayCommand<int>(IntTest, CanIntTest);
}
private bool CanTest(string text)
{
// the text must have a minimum length of 4
// and be different from the current one
return text != null && text.Length >= 4 && text != Text;
}
private void Test(string text)
{
Text = text;
}
private bool CanIntTest(int num)
{
// The "num" parameter must be positive, less than 100
// and is not equal to the Number property
return num > 0 && num <100 && num != Number;
}
private void IntTest(int num)
{
Number = num;
}
}
}
XAML:
<Window x:Class="InvalidateCommandMvvmLight.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:InvalidateCommandMvvmLight"
xmlns:vm="clr-namespace:InvalidateCommandMvvmLight.ViewModel"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<vm:MyViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBox x:Name="tbText"
Text="Alle eendjes zwemmen in het water" VerticalAlignment="Center"
/>
<Button Content="Change Text"
Grid.Column="1"
Margin="5"
Padding="5,2"
Command="{Binding Path=CommandTest}"
CommandParameter="{Binding ElementName=tbText, Path=Text}"/>
<TextBox Text="{Binding Text, Mode=OneWay}" Grid.Column="2" IsReadOnly="True" VerticalAlignment="Center"/>
<TextBox x:Name="tbNumber"
Grid.Row="1"
Text="55" VerticalAlignment="Center"/>
<Button Content="Change Number"
Grid.Row="1" Grid.Column="1"
Margin="5"
Padding="5,2"
Command="{Binding Path=CommandNumber}"
CommandParameter="{Binding ElementName=tbNumber, Path=Text}"/>
<TextBox Text="{Binding Number, Mode=OneWay}" IsReadOnly="True"
Grid.Row="1" Grid.Column="2" VerticalAlignment="Center"/>
</Grid>
</Window>
Unfortunately, the CommandsWpf.RelayCommand class in MvvmLight is implemented not correctly.
It does not take into account the peculiarities of working with values ​​of different types in WPF.
To work in a typical for WPF way, an implementation should have something like this:
using System.ComponentModel;
namespace Common
{
#region Delegates for WPF Command Methods
/// <summary>Delegate of the executive team method.</summary>
/// <param name="parameter">Command parameter.</param>
public delegate void ExecuteHandler<T>(T parameter);
/// <summary>Command сan execute method delegate.</summary>
/// <param name="parameter">Command parameter.</param>
/// <returns><see langword="true"/> if command execution is allowed.</returns>
public delegate bool CanExecuteHandler<T>(T parameter);
#endregion
/// <summary>Class for typed parameter commands.</summary>
public class RelayCommand<T> : RelayCommand
{
/// <summary>Command constructor.</summary>
/// <param name="execute">Executable command method.</param>
/// <param name="canExecute">Method allowing command execution.</param>
public RelayCommand(ExecuteHandler<T> execute, CanExecuteHandler<T> canExecute = null)
: base
(
p => execute(TypeDescriptor.GetConverter(typeof(T)).IsValid(p) ? (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(p) : default),
p => (canExecute == null) || (TypeDescriptor.GetConverter(typeof(T)).IsValid(p) && canExecute((T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(p)))
)
{}
}
}
Unless you have the ability to change the RelayCommand implementation, you need to somehow use Binding's ability to auto-convert values.
One variant.
Create a property of the desired type in the ViewModel and use it as a proxy for autoconversion.
But if a non-numeric value is entered, then the command will not be able to define it.
You also need to check Validation.HasError.
ViewModel:
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
namespace InvalidateCommandMvvmLight.ViewModel
{
public class MyViewModel : ViewModelBase
{
private string _text;
private int _number;
private int _numberView;
public string Text { get => _text; private set => Set(ref _text, value); }
public int Number { get => _number; set => Set(ref _number, value); }
public int NumberView { get => _numberView; set => Set(ref _numberView, value); }
public RelayCommand<string> CommandTest { get; }
public RelayCommand<int> CommandNumber { get; }
public MyViewModel()
{
CommandTest = new RelayCommand<string>(Test, CanTest);
CommandNumber = new RelayCommand<int>(IntTest, CanIntTest);
}
private bool CanTest(string text)
{
// the text must have a minimum length of 4
// and be different from the current one
return text != null && text.Length >= 4 && text != Text;
}
private void Test(string text)
{
Text = text;
}
private bool CanIntTest(int num)
{
// The "num" parameter must be positive, less than 100
// and is not equal to the Number property
return num > 0 && num <100 && num != Number;
}
private void IntTest(int num)
{
Number = num;
}
}
}
XAML:
<Window x:Class="InvalidateCommandMvvmLight.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:InvalidateCommandMvvmLight"
xmlns:vm="clr-namespace:InvalidateCommandMvvmLight.ViewModel"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<vm:MyViewModel NumberView="55"/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBox x:Name="tbText"
Text="Alle eendjes zwemmen in het water" VerticalAlignment="Center"
/>
<Button Content="Change Text"
Grid.Column="1"
Margin="5"
Padding="5,2"
Command="{Binding Path=CommandTest}"
CommandParameter="{Binding ElementName=tbText, Path=Text}"/>
<TextBox Text="{Binding Text, Mode=OneWay}" Grid.Column="2" IsReadOnly="True" VerticalAlignment="Center"/>
<TextBox x:Name="tbNumber"
Grid.Row="1"
Text="{Binding NumberView, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center"/>
<Button Content="Change Number"
Grid.Row="1" Grid.Column="1"
Margin="5"
Padding="5,2"
Command="{Binding Path=CommandNumber}"
CommandParameter="{Binding NumberView}">
<Button.Style>
<Style TargetType="Button">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=(Validation.HasError), ElementName=tbNumber}"
Value="True">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
<TextBox Text="{Binding Number, Mode=OneWay}" IsReadOnly="True"
Grid.Row="1" Grid.Column="2" VerticalAlignment="Center"/>
</Grid>
</Window>
Second variant.
Create an explicit proxy converter.
Converter:
using System;
using System.ComponentModel;
using System.Windows;
namespace InvalidateCommandMvvmLight
{
public class ProxyBinding : Freezable
{
public Type Type
{
get { return (Type)GetValue(TypeProperty); }
set { SetValue(TypeProperty, value); }
}
// Using a DependencyProperty as the backing store for Type. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TypeProperty =
DependencyProperty.Register(nameof(Type), typeof(Type), typeof(ProxyBinding), new PropertyMetadata(typeof(object), ChangedValueOrType));
private static void ChangedValueOrType(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ProxyBinding proxy = (ProxyBinding)d;
if (proxy.Type == null)
{
proxy.Value = null;
return;
}
if (proxy.Source == null)
return;
if (proxy.Type == proxy.Source.GetType())
return;
if (TypeDescriptor.GetConverter(proxy.Type).IsValid(proxy.Source))
proxy.Value = TypeDescriptor.GetConverter(proxy.Type).ConvertFrom(proxy.Source);
else
proxy.Value = null;
}
public object Source
{
get { return GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
// Using a DependencyProperty as the backing store for Value. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SourceProperty =
DependencyProperty.Register(nameof(Source), typeof(object), typeof(ProxyBinding), new PropertyMetadata(null, ChangedValueOrType));
public object Value
{
get { return GetValue(ValueProperty); }
protected set { SetValue(ValuePropertyKey, value); }
}
// Using a DependencyProperty as the backing store for readonly Value. This enables animation, styling, binding, etc...
protected static readonly DependencyPropertyKey ValuePropertyKey =
DependencyProperty.RegisterReadOnly(nameof(Value), typeof(object), typeof(ProxyBinding), new PropertyMetadata(null));
public static readonly DependencyProperty ValueProperty = ValuePropertyKey.DependencyProperty;
protected override Freezable CreateInstanceCore()
{
return new ProxyBinding();
}
}
}
XAML:
<Window x:Class="InvalidateCommandMvvmLight.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:InvalidateCommandMvvmLight"
xmlns:vm="clr-namespace:InvalidateCommandMvvmLight.ViewModel"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<vm:MyViewModel/>
</Window.DataContext>
<Window.Resources>
<local:ProxyBinding x:Key="ProxyInt"
Type="{x:Type sys:Int32}"
Source="{Binding ElementName=tbNumber, Path=Text, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBox x:Name="tbText"
Text="Alle eendjes zwemmen in het water" VerticalAlignment="Center"
/>
<Button Content="Change Text"
Grid.Column="1"
Margin="5"
Padding="5,2"
Command="{Binding Path=CommandTest}"
CommandParameter="{Binding ElementName=tbText, Path=Text}"/>
<TextBox Text="{Binding Text, Mode=OneWay}" Grid.Column="2" IsReadOnly="True" VerticalAlignment="Center"/>
<TextBox x:Name="tbNumber"
Grid.Row="1"
Text="55" VerticalAlignment="Center"/>
<Button Content="Change Number"
Grid.Row="1" Grid.Column="1"
Margin="5"
Padding="5,2"
Command="{Binding Path=CommandNumber}"
CommandParameter="{Binding Value, Source={StaticResource ProxyInt}}">
</Button>
<TextBox Text="{Binding Number, Mode=OneWay}" IsReadOnly="True"
Grid.Row="1" Grid.Column="2" VerticalAlignment="Center"/>
<TextBlock Grid.Row="2" Text="{Binding Value,Source={StaticResource proxy}}"/>
</Grid>
</Window>
Another variant.
Create converter for bindings:
using System;
using System.ComponentModel;
using System.Globalization;
using System.Windows.Data;
namespace InvalidateCommandMvvmLight
{
public class ValueTypeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter is Type type && TypeDescriptor.GetConverter(type).IsValid(value))
return TypeDescriptor.GetConverter(type).ConvertFrom(value);
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
XAML:
<Window x:Class="InvalidateCommandMvvmLight.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:InvalidateCommandMvvmLight"
xmlns:vm="clr-namespace:InvalidateCommandMvvmLight.ViewModel"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<vm:MyViewModel/>
</Window.DataContext>
<Window.Resources>
<local:ValueTypeConverter x:Key="ValueTypeConverter"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBox x:Name="tbText"
Text="Alle eendjes zwemmen in het water" VerticalAlignment="Center"
/>
<Button Content="Change Text"
Grid.Column="1"
Margin="5"
Padding="5,2"
Command="{Binding Path=CommandTest}"
CommandParameter="{Binding ElementName=tbText, Path=Text}"/>
<TextBox Text="{Binding Text, Mode=OneWay}" Grid.Column="2" IsReadOnly="True" VerticalAlignment="Center"/>
<TextBox x:Name="tbNumber"
Grid.Row="1"
Text="55" VerticalAlignment="Center"/>
<Button Content="Change Number"
Grid.Row="1" Grid.Column="1"
Margin="5"
Padding="5,2"
Command="{Binding Path=CommandNumber}"
CommandParameter="{Binding Text, Converter={StaticResource ValueTypeConverter}, ConverterParameter={x:Type sys:Int32}, ElementName=tbNumber}">
</Button>
<TextBox Text="{Binding Number, Mode=OneWay}" IsReadOnly="True"
Grid.Row="1" Grid.Column="2" VerticalAlignment="Center"/>
</Grid>
</Window>

How to bind visibiility and content of label based on validation done on the text entered by user in textbox?

I am writing simple application. The UI has two textboxes, for Username and Password, and button to submit the information. I wanted to use routed commands instead of buttonclick event.
Username should contain alphanumeric characters only, if user enter any other special characters, it should display a label saying invalid characters entered. So I wanted to bind the visibility and content of that label based on the validation done on Username textbox field.
Below is code I have made but it is not working as expected. Can any one help me where I am doing wrong?
Below my main Window
using System.Windows;
using System.Windows.Input;
using System.ComponentModel;
namespace ExcelUtility
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
ViewModel viewModelObj = new ViewModel();
public MainWindow()
{
InitializeComponent();
}
void navigatePageExecuted(object target, ExecutedRoutedEventArgs e)
{
SubmitUserDetails(txtUserName.Text + ";" + txtPassword);
}
void navigatePageCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (!string.IsNullOrWhiteSpace(txtUserName.Text))
{
viewModelObj.Username = txtUserName.Text;
}
e.CanExecute = viewModelObj.VaidUserName; }
private void SubmitUserDetails(string credentials)
{
this.Cursor = Cursors.Wait;
prgValidate.Visibility = Visibility.Visible;
MainGrid.IsEnabled = false;
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.RunWorkerAsync(credentials);
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
prgValidate.Visibility = Visibility.Collapsed;
string Result = (string)e.Result;
MessageBox.Show(Result); //Here I need to call some other functions based on return value for simplicity i have changed
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
string[] credentials = e.Argument.ToString().Split(';');
e.Result = viewModelObj.validateCredentials(credentials[0], credentials[1]);
}
}
}
This is my xaml
<Window x:Class="ExcelUtility.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ExcelUtility"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:BoolToVisibleOrHidden x:Key="BoolToVisibilityConverter"/>
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="{x:Static local:CommandsLibrary.navigatePageCommand}" Executed="navigatePageExecuted" CanExecute="navigatePageCanExecute"/>
</Window.CommandBindings>
<Grid Name="MainGrid">
<TextBlock Height="23" HorizontalAlignment="Left" Margin="40,44,0,0" Name="tbUserName" Text="Username" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="136,42,0,0" Name="txtUserName" VerticalAlignment="Top" Width="163" Text="{Binding Username, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="138,19,0,0" Name="tbNotify" Text="{Binding Notification, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="161" Visibility="{Binding NotVaidUserName,Converter={StaticResource BoolToVisibilityConverter}}" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="138,98,0,0" Name="txtPassword" VerticalAlignment="Top" Width="161" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="44,107,0,0" Name="tbPassword" Text="Password" VerticalAlignment="Top" Width="65" />
<Button Command="{x:Static local:CommandsLibrary.navigatePageCommand}" Content="Submit" Height="23" HorizontalAlignment="Left" Margin="172,167,0,0" Name="btnSubmit" VerticalAlignment="Top" Width="109" />
<ProgressBar Height="24" IsIndeterminate="True" Visibility="Collapsed" HorizontalAlignment="Left" Margin="52,232,0,0" Name="prgValidate" VerticalAlignment="Top" Width="257" />
</Grid>
</Window>
This is my viewModel
using System;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows;
namespace ExcelUtility
{
public class ViewModel
{
public event PropertyChangedEventHandler PropertyChanged;
private bool _notVaidUserName;
public bool NotVaidUserName
{
get { return _notVaidUserName; }
set
{
_notVaidUserName = value;
RaisePropertyChanged("NotVaidUserName");
}
}
private string notification;
public string Notification
{
get
{
return notification;
}
set
{
if (notification != value)
{
notification = value;
RaisePropertyChanged("Notification");
}
}
}
private string username;
public string Username
{
get
{
return username;
}
set
{
if (username != value)
{
username = value;
NotVaidUserName = VaidateUserName(username);
RaisePropertyChanged("Username");
}
}
}
public bool VaidateUserName(string strUsername)
{
bool bValidUserName = false;
if (!string.IsNullOrWhiteSpace(strUsername))
{
if (new Regex(#"^[a-zA-Z0-9]*$").IsMatch(strUsername))
{
bValidUserName = true;
if (strUsername.Length > 7)
{
Notification = "Max allowed key length is 6";
bValidUserName = false;
}
}
else
{
Notification = "No special characters allowed";
}
}
return bValidUserName;
}
public string validateCredentials(string Username, string Password)
{
return "Valid Credentials";
}
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
class BoolToVisibleOrHidden : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
object returnvalue = new object();
returnvalue = (bool)value ? Visibility.Visible : parameter != null ? Visibility.Collapsed : Visibility.Hidden;
return returnvalue;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return (Visibility)value == Visibility.Visible;
}
}
}
First define two properties like below:
private bool isValid = true;
public bool IsValid
{
get
{
return isValid;
}
set
{
if (isValid != value)
{
isValid = value;
OnPropertyChanged("IsValid");
}
}
}
private string username;
public string Username
{
get
{
return username;
}
set
{
if(username != value)
{
username = value;
IsValid = ValidateForSpecialCharacters(username);
OnPropertyChanged("Username");
}
}
}
Then bind them to your xaml like this:
<TextBlock Text="Username contains special characters."
Visibility="{Binding IsValid,Converter={StaticResource BoolToVisibilityConverter}}" />
<TextBox Text="{Binding Username, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" />
PS: Don't forget to implement BoolToVisibility converter class and ValidateForSpecialCharacter method. I think you can handle it on your own. By the way, if I were you, I would use ValidationRule instead of this way.
Hope this help.
You must create a boolToVis converter, which convert False to collapsed and True to visible.
After this, you can bind the bool value to the visibility property of your item.
This is the converter (you can put this in a single file and call it from xaml):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace yourNamespace.ViewModel
{
[ValueConversion(typeof(bool), typeof(bool))]
public class InverseBooleanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (value is bool)
{
return !(bool)value;
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (value is bool)
{
return !(bool)value;
}
return value;
}
}
}
then, from your xaml, at the the beginning of the file:
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis"/>
</UserControl.Resources>
or if you use a window:
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis"/>
</Window.Resources>
then, finally, in your textBox:
<dxe:TextEdit Visibility="{Binding YOURBOOLFLAG, Converter={StaticResource BoolToVis}}" EditValue="TextHere"/>
(TextEdit is a devexpress element; you can also use the classic textBox in the same way)
in this way, when you see that the text is not correct for you, you can set the bool flag to false and hide the element.
You could simply implement a converter that check the username character like so:
class VisibilityConverter:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var rgx = new Regex(#"^[a-zA-Z0-9]*$");
if (value == null) return Visibility.Hidden;
return (rgx.IsMatch(value.ToString()))?Visibility.Hidden:Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
don't forget to add the converter to the window resources
<Window.Resources>
<conv:VisibilityConverter x:Key="VisibilityConverter"/>
</Window.Resources>
and finally use that converter in your UI to check the string entered in the textBox
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="Username" Grid.Column="0" Grid.Row="0"/>
<TextBlock Text="Password" Grid.Column="0" Grid.Row="1"/>
<TextBox Grid.Column="1" Grid.Row="0" Text="{Binding Username,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Grid.Column="1" Grid.Row="1" Text="{Binding Password,Mode=TwoWay}"/>
<Button Content="login" IsEnabled="{Binding Username,Converter={StaticResource VisibilityConverter},Mode=TwoWay}" Grid.Column="1" Grid.Row="2"/>
<TextBlock Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" Text="invalid characters entered" VerticalAlignment="Center" HorizontalAlignment="Center" Visibility="{Binding Username,Converter={StaticResource VisibilityConverter}}"></TextBlock>
</Grid>

the type imageconverter was not found

i'm trying to apply a converter for my image source binding. here's my xaml:
<Window.Resources>
<DataTemplate x:Key="listBoxTemplate">
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
<ImageConverter x:Key="MyImageConverter" />
</StackPanel.Resources>
<Image Source="{Binding Path=thumb, StringFormat=/WpfTest;component/Images/{0}, Converter={StaticResource MyImageConverter}}" Height="100" Width="130" Margin="5"></Image>
<StackPanel Orientation="Vertical" Width="247">
<TextBlock Text="{Binding recipeName}" Height="60" Padding="15" FontSize="16" HorizontalAlignment="Stretch" VerticalAlignment="Center"></TextBlock>
<TextBlock Text="{Binding cuisine}" Height="60" Padding="15" FontSize="16" HorizontalAlignment="Stretch" VerticalAlignment="Center"></TextBlock>
</StackPanel>
</StackPanel>
</DataTemplate>
</Window.Resources>
and here's my imageConverter class:
using System;
using System.Windows.Data;
using System.Globalization;
using System.Windows.Media.Imaging;
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string path = (string)value;
try
{
//ABSOLUTE
if (path.Length > 0 && path[0] == System.IO.Path.DirectorySeparatorChar
|| path.Length > 1 && path[1] == System.IO.Path.VolumeSeparatorChar)
return new BitmapImage(new Uri(path));
//RELATIVE
return new BitmapImage(new Uri(System.IO.Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar + path));
}
catch (Exception)
{
return new BitmapImage();
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
but when i tried running the apps, it returns "the type imageconverter was not found" and VS highlight the part
<ImageConverter x:Key="MyImageConverter" />
in the xaml above. How do I fix it? (Btw I got the imageconverter code from Wpf - relative image source path )
You need to add its namespace like this:
<ns:ImageConverter x:Key="MyImageConverter"/>
And make sure you added the namespace higher up like this:
<DataTemplate xmlns:ns="....">
The actual namespace depends on you project but code completion will help you.

Silverlight BusyIndicator

Is there a way to not show the BusyIndicator when it is not busy (IsBusy='false')? After I added the silverlight BusyIndicator into my UserControl it uses a large area so all other controls are moved down and the GUI looks not good anymore. I need it is hided when it's no busy and shows up when it's busy.
Thanks for help.
CK
I would use a standard BooleanToVisiblityConverter and bind the Visibilty to the IsBusy property like such:
<Grid Height="500" Width="500" Background="Blue">
<Grid.Resources>
<Converters:BoolToVisConverter x:Key="BoolToVis"/>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel Width="75">
<ToggleButton x:Name="BusyButton" Content="Toggle Busy State"/>
<ToggleButton x:Name="ProgressButton" Content="Toggle ProgressButton State"/>
</StackPanel>
<toolkit:BusyIndicator Grid.Row="1" IsBusy="{Binding IsChecked, ElementName=BusyButton}"
Visibility="{Binding IsBusy, RelativeSource={RelativeSource Self}}"/>
<ProgressBar Grid.Row="2" Width="120" Height="10" Margin="4 2" VerticalAlignment="Center" IsIndeterminate="True"
Visibility="{Binding IsChecked, ElementName=ProgressButton, Converter={StaticResource BoolToVis}}"/>
</Grid>
I've provided both a BusyIndicator as well as ProgressBar is this example so you can see both in action.
The BooleanToVisibilityConverter is pretty standard and is implemented as such:
public class BoolToVisConverter : IValueConverter
{
#region IValueConverter Members
public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return Visibility.Collapsed;
return (bool)value == true ? Visibility.Visible : Visibility.Collapsed;
}
public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}

WPF: TwoWay binding between 4 TextBoxes and 1 Border.Margin

I want to set the BorderThickness of a Border of a UserControl using 4 TextBoxes, but I can't get it to work.
XAML code demonstrating the problem (only this code in combination with the converter is needed):
<Window
x:Class="BorderThicknessBindingTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:BorderThicknessBindingTest="clr-namespace:BorderThicknessBindingTest"
Height="300" Width="500">
<Window.Resources>
<BorderThicknessBindingTest:ThicknessConverter x:Key="ThicknessConverter"/>
</Window.Resources>
<Grid Margin="10">
<Border
x:Name="MyBorder"
BorderBrush="Black"
Background="AliceBlue"
BorderThickness="3"/>
<TextBox
HorizontalAlignment="Center" VerticalAlignment="Center"
Text="{Binding Path=BorderThickness.Left, ElementName=MyBorder, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource ThicknessConverter}}"/>
</Grid>
</Window>
A converter is needed to parse the string input in the TextBox:
public class ThicknessConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value; // don't need to do anything here
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
double d;
Double.TryParse((string) value, out d); // Thickness.Left doesn't take a string
return d;
}
}
The TextBox correctly displays the Left part of the Thickness, but editing the TextBox does not result in a change in the way the left side of the Border is rendered. Oddly, the value that I set in the TextBox for Thickness.Left persists, so it seems that the value does get set, but the rendering isn't updated.
In the example code, changing the value in the TextBox, then resizing the Window, shows that the border on the left does take up additional space, but this space is blank.
Does anyone know how to go about and fixing this?
It's not dynamically updating the element on the screen because nothing has told the element that a field in its BorderThickness property has changed. You need to notify the element that its BorderThickness has changed, which you can only do by directly setting the dependency property to a new value - say, by making it the target of a binding to an object that does change notification.
It's something of a pain to make a view model for this, but once you do, it's done.
The window:
<Window x:Class="ThicknessDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ComponentModel="clr-namespace:System.ComponentModel;assembly=System" xmlns:ThicknessDemo="clr-namespace:ThicknessDemo" Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ThicknessDemo:ThicknessViewModel x:Key="thickness" />
</Window.Resources>
<DockPanel DataContext="{StaticResource thickness}">
<Border DockPanel.Dock="Top"
Width="100"
Height="50"
Margin="5"
BorderBrush="Blue"
BorderThickness="{Binding Thickness}" />
<TextBox DockPanel.Dock="Top"
Text="{Binding Left, Mode=TwoWay}" />
<TextBox DockPanel.Dock="Top"
Text="{Binding Right, Mode=TwoWay}" />
<TextBox DockPanel.Dock="Top"
Text="{Binding Top, Mode=TwoWay}" />
<TextBox DockPanel.Dock="Top"
Text="{Binding Bottom, Mode=TwoWay}" />
<TextBlock DockPanel.Dock="Top" />
</DockPanel>
</Window>
The view model:
public class ThicknessViewModel : INotifyPropertyChanged
{
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler h = PropertyChanged;
if (h != null)
{
h(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public ThicknessViewModel()
{
_Thickness = new Thickness(1, 1, 1, 1);
}
private Thickness _Thickness;
public Thickness Thickness { get { return _Thickness; } set { _Thickness = value;} }
public double Left
{
get { return _Thickness.Left; }
set
{
_Thickness.Left = value;
OnPropertyChanged("Thickness");
}
}
public double Right
{
get { return _Thickness.Right; }
set
{
_Thickness.Right = value;
OnPropertyChanged("Thickness");
}
}
public double Top
{
get { return _Thickness.Top; }
set
{
_Thickness.Top = value;
OnPropertyChanged("Thickness");
}
}
public double Bottom
{
get { return _Thickness.Bottom; }
set
{
_Thickness.Bottom = value;
OnPropertyChanged("Thickness");
}
}
}
I believe this will point you in the right direction: Read halfway down it has 2 ways of approaching this, one with a converter and one without.
http://10rem.net/blog/2010/05/08/breaking-apart-the-margin-property-in-xaml-for-better-binding
The simplest solution for me turns out to be to just listen to the TextChanged event of the TextBox, and replace the BorderThickness in code behind.
MainWindow.xaml:
<Window
x:Class="BorderThicknessBindingTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:BorderThicknessBindingTest="clr-namespace:BorderThicknessBindingTest"
Height="300" Width="500">
<Grid Margin="10">
<Border
x:Name="MyBorder"
BorderBrush="Black"
Background="AliceBlue"
BorderThickness="3"/>
<TextBox
x:Name="MyTextBox"
HorizontalAlignment="Center" VerticalAlignment="Center"
Text="{Binding Path=BorderThickness.Left, ElementName=MyBorder, Mode=OneWay}"/>
</Grid>
</Window>
MainWindow.xaml.cs, in the constructor:
MyTextBox.TextChanged += (sender, e) =>
{
double d;
if (!double.TryParse(MyTextBox.Text, out d)) return;
var t = MyBorder.BorderThickness;
t.Left = d;
MyBorder.BorderThickness = t;
};
Right now this works for me, Robert Rossney's solution is better.

Resources