I have a XamDataGrid with 2 fields. In the second field, I have toggle buttons. When the ToggleButton is clicked, the value gets set correctly. But at any time user should be able to check only one ToggleButton among all the records. The data in the set logic for the Default property works fine. But I need to set the values of Default for other items in DataSource.
Using a RadioButton instead of ToggleButton would the ideal solution. But it is possible that none of the records are default. So I want a solution to make the other default fields false when one of them becomes true.
XAML for field:
<igWPF:Field Name="Default" Width="84">
<igWPF:Field.Settings>
<igWPF:FieldSettings CellValuePresenterStyle="{StaticResource ButtonDefault}" />
</igWPF:Field.Settings>
</igWPF:Field>
XAML for CellValuePresenterStyle:
<Style x:Key="ButtonDefault" TargetType="{x:Type igWPF:CellValuePresenter}" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type igWPF:CellValuePresenter}">
<ToggleButton Content="Default"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="16"
Width="80"
Height="36"
IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Datasource:
public class LanguageSettingItem : INotifyPropertyChanged
{
private string name;
private bool isDefault;
public event PropertyChangedEventHandler PropertyChanged;
public string Name
{
get { return this.name; }
set { this.name = value; PropChanged("Name"); }
}
public bool Default
{
get { return this.isDefault; }
set { this.isDefault= value; PropChanged("Default"); }
}
public void PropChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
You can have Toggle Button event Checked and Unchecked with same event Handler.
Then just put a if condition - (if toggle_btn.isChecked)'checked code' else 'unchecked code'
Related
I have made a custom button, since I would like to be able to set to differents strings, independantly, for the content. I have then made a ControlTemplate in my xaml, to specify how the two contents should be rendered. The content is bound to sub-properties of a selected item (from a list view). I am using INotifyPropertyChanged to notify the view, if the selection changed. And then the content and sub-content of my button, should change accordingly.
Now this works fine for the content. But the sub-content only displays anything, when the program is first loaded. After the first change in selection, it goes blank, and stays blank.
Have I missed something? Is there anything else I need to add?
Custom button C#
public class DoubleContentButton : Button
{
static DoubleContentButton() { }
public object SubContent
{
get => GetValue(SubContentProperty);
set => SetValue(SubContentProperty, value);
}
public static readonly DependencyProperty SubContentProperty =
DependencyProperty.Register(name: "SubContent", typeof(object), typeof(DoubleContentButton), new UIPropertyMetadata());
}
Custom button control template
<Style x:Key="StatusButton" TargetType="{x:Type custom:DoubleContentButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type custom:DoubleContentButton}">
<StackPanel Margin="0 0 0 20">
<!-- This updates -->
<TextBlock Text="{TemplateBinding Content}"/>
<!-- This does not update -->
<TextBlock Text="{TemplateBinding SubContent}" />
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Implementation of button
<custom:DoubleContentButton
Command="{Binding MyCommand}"
Content="{Binding SelectedItem.Status}"
SubContent="{Binding SelectedItem.SubStatus}"
Style="{StaticResource StatusButton}" />
Can you check if your SubStatus property has a PropertyChangedEventHandler raised on the setter of the "SubStatus" or if it has, is it properly raised?
Like this:
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyRaised(string propertyname)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
}
public string SubStatus
{
get { ... }
set
{
_SubStatus = value;
OnPropertyRaised(nameof(SubStatus));
}
}
I'm trying to display a control in the xaml if the property ConnectionStatus is True, this property have the following structure:
private bool _connectionStatus = true;
public bool ConnectionStatus
{
get { return _connectionStatus; }
set
{
_connectionStatus = value;
OnPropertyChanged();
}
}
and as you can see this property have true as default value.
Then in my xaml window I've used a DataTrigger to show or hide the control based on the ConnectionStatus value. What I did so far:
<StackPanel Grid.Column="1">
<StackPanel.Style>
<Style TargetType="StackPanel">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding ConnectionStatus}" Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</StackPanel.Style>
<Ellipse Fill="#FF51FF00" Height="17" Width="17" Margin="0,5,0,0" StrokeThickness="1" Stroke="White" />
</StackPanel>
now the problem's that the Ellipse simply not showing, 'cause the whole StackPanel is collapsed, but it shouldn't 'cause the property value is True, when I set False in the xaml code, I get the Ellipse displayed correctly.
Note that: this situation only happen on the preview window, if I start the application all working good. Someone could please explain me why in the preview the trigger doesn't read the property value correctly?
Further information
the window that have the StackPanel have the DataContext declared in this way:
xmlns:local="clr-namespace:MyApp.MVVM.ViewModels"
d:DataContext="{d:DesignInstance local:ConnectionVM}">
then the ConnectionVM have this implementation:
public class ConnectionVM: ViewModel
{
//the property defined on top
}
and the ViewModel have this structure:
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
}
Thanks.
I have the following INotifyDataErrorInfo implementation in an abstract base class.
private IEnumerable<ValidationErrorModel> _validationErrors = new List<ValidationErrorModel>();
public IEnumerable<ValidationErrorModel> ValidationErrors
{
get { return _validationErrors; }
private set
{
_validationErrors = value;
OnPropertyChanged();
}
}
protected abstract Task<ValidationResult> GetValidationResultAsync();
public IEnumerable GetErrors(string propertyName)
{
if (string.IsNullOrEmpty(propertyName) ||
ValidationErrors == null)
return null;
IEnumerable<string> errors = ValidationErrors
.Where(p => p.PropertyName.Equals(propertyName))
.Select(p => p.ToString())
.ToList();
return errors;
}
public bool HasErrors
{
get
{
bool hasErrors = ValidationErrors != null && ValidationErrors.Any();
return hasErrors;
}
}
public Task<ValidationResult> ValidateAsync()
{
Task<ValidationResult> validationResultTask = GetValidationResultAsync();
validationResultTask.ContinueWith((antecedent) =>
{
if (antecedent.IsCompleted &&
!antecedent.IsCanceled &&
!antecedent.IsFaulted)
{
ValidationResult validationResult = antecedent.Result;
if (validationResult != null)
{
lock (ValidationErrors)
{
ValidationErrors =
validationResult.Errors
.Select(validationFailure =>
new ValidationErrorModel(validationFailure.PropertyName, validationFailure.ErrorMessage))
.ToList();
foreach (ValidationErrorModel validationErrorModel in ValidationErrors)
{
RaiseErrorsChanged(validationErrorModel.PropertyName);
}
}
}
}
});
return validationResultTask;
}
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged = delegate { };
protected virtual void RaiseErrorsChanged(string propertyName)
{
var handler = ErrorsChanged;
if (handler != null)
{
Dispatcher.InvokeOnMainThread(() =>
{
handler(this, new DataErrorsChangedEventArgs(propertyName));
});
}
}
In models deriving from the base class I implement the Task<ValidationResult> GetValidationResultAsync() required method, it uses fluent validation Nuget package.
private readonly ModelValidator _modelValidator = new ModelValidator();
protected override Task<ValidationResult> GetValidationResultAsync()
{
return _modelValidator.ValidateAsync(this);
}
The problem is that when I invoke from a ViewModel the ValidateAsync() method of a model the UI input controls are not invalidate/validate correctly, I actually have a tab control and validate the models in tab index changed, some might show the red border once I change tab but then again return to normal state to the next tab change.
In debug it shows that the ValidationErrors property returns errors.
My XAML input controls code is like below.
<Grid>
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Name:"/>
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, ValidatesOnNotifyDataErrors=True}" Width="200"/>
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Scheduled Date:"/>
<DatePicker DisplayDate="{Binding ScheduledDate, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, ValidatesOnNotifyDataErrors=True}"/>
</StackPanel>
</StackPanel>
</Grid>
[Update 1]
I should mention that I use in the MainWindow a tab control and 3 tab items, each tab item is a UserControl.
I hooked up to the Validation.Error event of all the XAML UserControls and I noticed that even I get tab selected index changed value the Validation.Error fires once for the first tab and never again, I suspect there is a cleanup somewhere for a reason.
Code for the SelectedTabIndex that fires the models validations.
private int _selectedTabIndex = 0;
public int SelectedTabIndex
{
get { return _selectedTabIndex; }
set
{
_selectedTabIndex = value;
ValidateModels();
Tab2ViewModel.ValidateModels();
Tab3ViewModel.ValidateModels();
OnPropertyChanged();
}
}
The ValidateModels method calls ValidateAsync of the model in the ViewModel.
public override Task ValidateModels()
{
return Model.ValidateAsync();
}
MainWindow TabControl XAML.
<TabControl SelectedIndex="{Binding SelectedTabIndex, Mode=TwoWay}">
[Update 2]
After adding a custom error style and a custom error template, I see that the controls tooltip stay with the condition not met error but the error template is clearing. So, the TextBox shows no error template, custom or default, but the validation error exists and the tooltip shows the error.
Why the XAML templates clear on TabIndexChange and how come they don't refresh at least on the active tab item I'm viewing. This might be the problem that I should solve.
Also, as mentioned before, I don't see the ErrorsChanged revalidating the controls except the first time the SelectedTabIndex setter is invoked.
The templates I added.
<Application.Resources>
<Style x:Key="ErrorStyle"
TargetType="FrameworkElement">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip" Value="{Binding (Validation.Errors).CurrentItem.ErrorContent, RelativeSource={x:Static RelativeSource.Self}}"></Setter>
</Trigger>
</Style.Triggers>
</Style>
<ControlTemplate x:Key="TextBoxErrorTemplate">
<DockPanel>
<Ellipse DockPanel.Dock="Right"
Margin="2,0"
ToolTip="Contains Invalid Data"
Width="10"
Height="10"
>
<Ellipse.Fill>
<LinearGradientBrush>
<GradientStop Color="#11FF1111" Offset="0"/>
<GradientStop Color="#FFFF0000" Offset="1"/>
</LinearGradientBrush>
</Ellipse.Fill>
</Ellipse>
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>
<Style TargetType="TextBox">
<Setter Property="Margin" Value="4,4,15,4"/>
<Setter Property="Validation.ErrorTemplate" Value="{StaticResource TextBoxErrorTemplate}"/>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip">
<Setter.Value>
<Binding Path="(Validation.Errors).CurrentItem.ErrorContent" RelativeSource="{x:Static RelativeSource.Self}"/>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</Application.Resources>
The problem is that tabs, expanders etc don't work well with validators, you need to include AdornerDecorator, or not use tabs which in my case is not an option.
Issue with WPF validation(IDataErrorInfo) and tab focusing.
i think i have read already all related articles but non of them help..
im trying to enable/disable a save button of datagrid by the error state- but with no success.
this is my code:
contractor:
AddHandler(Validation.ErrorEvent, new RoutedEventHandler(OnErrorEvent));
XAML:
<Page
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:col="clr-namespace:System.Collections;assembly=mscorlib"
xmlns:local="clr-namespace:Metsuka_APP" x:Class="Metsuka_APP.MichlolimManagment"
mc:Ignorable="d"
d:DesignHeight="500" d:DesignWidth="500"
Title="MichlolimManagment"
x:Name="Michlolim_Managment" Validation.Error="Michlolim_Managment_Error">
<Page.Resources>
<DataGrid x:Name="AGAFIMDataGrid" VerticalAlignment="Center" RowEditEnding="rowEditEnding" Margin="10" FlowDirection="RightToLeft" Height="340"
AutoGenerateColumns="False" EnableRowVirtualization="True"
ItemsSource="{Binding Source={StaticResource aGAFIMViewSource}}" Grid.Row="1"
RowDetailsVisibilityMode="VisibleWhenSelected"
ScrollViewer.CanContentScroll="True"
ScrollViewer.VerticalScrollBarVisibility="Auto"
HorizontalGridLinesBrush="Silver"
VerticalGridLinesBrush="Silver">
<DataGrid.Resources>
<Style x:Key="errorStyle" TargetType="{x:Type TextBox}">
<Setter Property="Padding" Value="-2"/>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="Background" Value="Red"/>
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn x:Name="agaf_nameColumn" Header="name" Width="*">
<DataGridTextColumn.Binding>
<Binding Path="agaf_name" NotifyOnValidationError="True" >
<Binding.ValidationRules>
<local:MichlolimValidationRule ValidationStep="UpdatedValue"/>
</Binding.ValidationRules>
</Binding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
</DataGrid.Columns>
<DataGrid.RowValidationErrorTemplate>
<ControlTemplate>
<Grid Margin="0,-2,0,-2"
ToolTip="{Binding RelativeSource={RelativeSource
FindAncestor, AncestorType={x:Type DataGridRow}},
Path=(Validation.Errors)[0].ErrorContent}">
<Ellipse StrokeThickness="0" Fill="Red"
Width="{TemplateBinding FontSize}"
Height="{TemplateBinding FontSize}" />
<TextBlock Text="!" FontSize="{TemplateBinding FontSize}"
FontWeight="Bold" Foreground="White"
HorizontalAlignment="Center" />
</Grid>
</ControlTemplate>
</DataGrid.RowValidationErrorTemplate>
</DataGrid>
code behind:
private int errorCount;
private void OnErrorEvent(object sender, RoutedEventArgs e)
{
var validationEventArgs = e as ValidationErrorEventArgs;
if (validationEventArgs == null)
throw new Exception("Unexpected event args");
switch (validationEventArgs.Action)
{
case ValidationErrorEventAction.Added:
{
errorCount++; break;
}
case ValidationErrorEventAction.Removed:
{
errorCount--; break;
}
default:
{
throw new Exception("Unknown action");
}
}
btnSavePop.IsEnabled = errorCount == 0;
}
but the "OnErrorEvent" never fires- any idea why?
You need to set NotifyOnValidationError="True" on your bindings - otherwise, the event won't be raised. I would recommend using the IDataErrorInfo or INotifyDataErrorInfo interfaces instead for an MVVM error handling approach.
Try creating a class like the following:
public class AgafDescriptor : INotifyPropertyChanged, IDataErrorInfo
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
if (_name != value)
{
_name = value;
RaisePropertyChanged(x => x.Name);
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged<T>(Expression<Func<AgafDescriptor, T>> propertyExpression)
{
PropertyChangedEventHandler localPropertyChanged = this.PropertyChanged as PropertyChangedEventHandler;
if ((localPropertyChanged != null) && (propertyExpression != null))
{
MemberExpression body = propertyExpression.Body as MemberExpression;
if (body != null)
{
localPropertyChanged(this, new PropertyChangedEventArgs(body.Member.Name));
}
}
}
#endregion
#region IDataErrorInfo Members
// Does nothing in WPF.
public string Error
{
get { return null; }
}
public string this[string columnName]
{
get
{
string returnVal = null;
if (string.Equals("Name", columnName, StringComparison.Ordinal))
{
if (string.IsNullOrWhiteSpace(Name))
{
returnVal = "A name must be supplied.";
}
}
return returnVal;
}
}
#endregion
}
This will provide an error whenever there is a change to the Name property. Please note that if you wish to trigger new validation checks without modifying the property you just need to call:
RaisePropertyChanged(x => x.Name);
You will then need to change your binding to something like:
<DataGridTextColumn x:Name="agaf_nameColumn" Header="name" Width="*" Binding="{Binding Name, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, NotifyOnValidationError=True}"/>
Note you will have to load your data from the DB and create a descriptor for each item you want to display in the DataGrid.
The reason behind why you aren't seeing the event being fired:
You aren't raising property change events (INotifyPropertyChanged or through a DependencyProperty) therefore the UI won't receive updates and the event won't be fired because it hasn't received an update to then perform the validation. By binding direct to your DB then you aren't raising the property change events. You can see that the Name property I suggested in my answer does raise the property changed event
The attribute
Validation.Error="Michlolim_Managment_Error"
in your XAML already sets a handler for the error event on the window level, however, to a method which isn't defined in your code behind fragment. Your AddHandler call looks ok, but, depending on where it is in the constructor, it might get overridden by the XAML event handler definition.
Probably not related, but you might want to change
(Validation.Errors)[0].ErrorContent
to
(Validation.Errors)/ErrorContent
in your ToolTip bindings, since the former causes binding errors if there are no errors. Unfortunately, it is still contained in the documentation samples...
From my sample of your code I think you are missing specifying UpdateSourceTrigger="PropertyChanged" or UpdateSourceTrigger="LostFocus" on the DataGridTextColumn in the DataGrid instead of using the default behavior of the DataGrids binding.
That is assuming my assumptions are correct see bottom.
Your code causes OnErrorEvent to fire if i change:
<DataGridTextColumn.Binding>
<Binding Path="agaf_name" NotifyOnValidationError="True" >
...
To include UpdateSourceTrigger for PropertyChanged or LostFocus like so:
<DataGridTextColumn.Binding>
<Binding Path="agaf_name" NotifyOnValidationError="True" UpdateSourceTrigger="PropertyChanged" >
....
Assumptions - For your ValidationRule to test i made it always return false (see below). And for the test item source i am binding to a string value in 'agaf_name' property.
public class MichlolimValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
return new ValidationResult(false, "bad");
}
}
I am trying to link the visibility of a TextBlock to a bool property which is also linked to a checkbox using WPF and c#. I have the following code in two different sections of the same xaml file (one section is a summary, and the other is settings. I am very new to WPF, and am learning as I go. Currently, the TextBlock is visible no matter what the value of IsSecondaryMessageFilePath is.
<TextBlock Name="secondaryfolderinfo" Foreground="Red">
<ContentControl Content="Secondary message folder" Foreground ="Black" />
<ContentControl Content = "{Binding Path=SecondaryMessageFilePath}" ContentStringFormat="" ClipToBounds="False"></ContentControl>
<ContentControl Content = " "></ContentControl>
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsSecondaryMessageFilePath}" Value="True">
<Setter Property="Visibility" Value="Visible"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
Further down I have:
<CheckBox IsChecked="{Binding Path=IsSecondaryMessageFilePath, Mode=TwoWay}"
Name="SecondaryPathCheckBox"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Margin="320,7,0,0">Save additional locations</CheckBox>
Finally, in the code-behind, I have:
public bool IsSecondaryMessageFilePath
{
get { return _isSecondaryMessageFilePath; }
set
{
if (_isSecondaryMessageFilePath != value)
{
_isSecondaryMessageFilePath = value;
OnPropertyChanged("IsSecondaryMessageFilePath");
}
}
}
private bool _isSecondaryMessageFilePath;
public string SecondaryMessageFilePath
{
get { return _secondaryMessageFilePath; }
set
{
if (_secondaryMessageFilePath != value)
{
_secondaryMessageFilePath = value;
OnPropertyChanged("SecondaryMessageFilePath");
}
}
}
private string _secondaryMessageFilePath;
Any assistance would be appreciated.
EDIT
Working from the suggestion below, I tried adding the BooleanToVisibilityConverter, but am getting a missing assembly reference for it, and am to new to WPF to figure out how to resolve it. My opening code is as follows:
<UserControl x:Class="Sender_Receiver.SenderReceiverSetup"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:diagnostics="clr-namespace:System.Diagnostics;assembly=WindowsBase"
xmlns:m=...
xmlns:
<UserControl.Resources>
<BooleanToVisibiltyConverter x:Key="BooleanToVisibilityConverter"/>
...
Your code looks ok at first glance, but you really don't need to use a data trigger for this. WPF comes with a BooleanToVisibilityConverter class that you declare in your resources:
<BooleanToVisibiltyConverter x:Key="BooleanToVisibilityConverter"/>
Then in your TextBlock, you bind Visibility:
<TextBlock Visibility="{Binding Path=IsSecondaryMessageFilePath, Converter={StaticResource BooleanToVisibilityConverter}}"/>
Just so you know, there may be a simpler way to do this, just bind to the IsChecked property itself!
<CheckBox x:Name="UseSecondaryPath"/>
<TextBlock Visibility="{Binding ElementName=UseSecondaryPath, Path=IsChecked, Converter={StaticResource BooleanToVisibilityConverter}}"/>
Of course if you need the bool for something else that wouldn't be an ideal solution, but it is a little cleaner if its just for the UI.
The code for a custom BooleanToVisibilityConverter, if you are interested, is:
public class BooleanToVisibilityConverter : IValueConverter
{
public object Convert (object value, ...)
{
if ((bool)value)
return Visibility.Visible;
else
return Visibility.Collapsed;
}
public object ConvertBack(object value, ...)
{
return Binding.DoNothing;
}
}
Let me know if I can clarify anything or assist further.
private Boolean _IsChecked;
//Bind this to your checkbox
public Boolean IsChecked
{
get { return _IsChecked; }
set { _IsChecked= value; OnPropertyChanged("IsChecked"); OnPropertyChanged("TextBoxVis"); }
}
//Bind this to your TextBox's Visibility Property
public Visibility TextBoxVis
{
get { return IsChecked ? Visibility.Visible : Visibility.Collapsed; }
}