I would show/hide textbox based on checkbox selection (if checked, show the textbox filed).
I tried this way, but it does't work ( the textbox field is always hidden):
<CheckBox x:Name="chkpsw" IsChecked="{ Binding PasswordRequired, Mode=TwoWay}" />
<TextBox Text="{Binding Password,Mode=TwoWay}" Visibility="{Binding PasswordRequired, Converter={StaticResource VisibilityConverter}}"/>
PasswordRequired is a bool property, Password is a string property,
VisibilityConverter:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool visibility = (bool)value;
return visibility ? Visibility.Visible : Visibility.Collapsed;
}
My Model:
private bool _passwordRequired;
...
public bool PasswordRequired
{
get { return _passwordRequired; }
set
{
_passwordRequired = value;
OnPropertyChanged("PasswordRequired");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
Related
Good morning
I have a problem with binding initial state for each radio button.
<StackLayout Orientation="Horizontal"
RadioButtonGroup.GroupName="{Binding Source}"
RadioButtonGroup.SelectedValue="{Binding Frequency}">
<RadioButton FontSize="10" Content="Never" Value="0"/>
<RadioButton FontSize="10" Content="Rare" Value="25"/>
<RadioButton FontSize="10" Content="Often" Value="75"/>
<RadioButton FontSize="10" Content="Always" Value="100"/>
</StackLayout>
When the view is loaded there is no any RadioButton selected. The source binding Frequency is of type double.
public double Frequency
{
get => GetPropertyValue<double>();
set => SetPropertyValue(value);
}
I was thinking it is related with comparassion of types object and double. I have created converter as below:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!int.TryParse(value.ToString(), out var intValue))
return value;
var result = FrequencyValues.GetValue(intValue).ToString();
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (!int.TryParse(value.ToString(), out var intValue))
return value;
var result = FrequencyValues.GetValue(intValue);
return result;
}
The solution with converter is also not working. Is that related with comprassion of types or I am missing some knowledge?
Thanks!
try
<StackLayout
RadioButtonGroup.GroupName="Source"
RadioButtonGroup.SelectedValue="{Binding Frequency}"
>
<RadioButton Content="a" Value="1"
IsChecked="{Binding Frequency, Converter={StaticResource RadioIsCheckedConverter}, ConverterParameter={x:Reference page}}" />
<RadioButton Content="b" Value="2"
IsChecked="{Binding Frequency, Converter={StaticResource RadioIsCheckedConverter}, ConverterParameter={x:Reference page}}" />
</StackLayout>
converter
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null)
{
var radioButton = parameter as RadioButton;
if (radioButton != null && radioButton.Value.Equals(value))
{
return true;
}
}
return false;
}
Change the type of Frequency from Double to Object;
The same Xaml as yours.
Code behind:
public partial class Page1 : ContentPage
{
RadioButtonModel _viewModel;
public Page1()
{
InitializeComponent();
_viewModel = new RadioButtonModel() { Source = "Group1", Frequency="100" };
this.BindingContext = _viewModel;
}
}
public class RadioButtonModel : INotifyPropertyChanged
{
private object _frequency;
public object Frequency
{
get => _frequency;
set
{
_frequency = value;
GetPropertyValue(nameof(Frequency));
}
}
private string _source;
public string Source
{
get => _source;
set
{
_source = value;
GetPropertyValue(nameof(Source));
}
}
public event PropertyChangedEventHandler PropertyChanged;
void GetPropertyValue(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
We have used DataGridTemplateColumn for our grid to display texbox under each column. We've a requirement to make the textboxes readonly if it contains any data (for data loading case). In order to achieve that, we need to access all text box controls under the radgrid. We've tried following approaches so far
Find all child controls using VisualTreeHelper - No textbox control was found
Tried with DataBindingComplete event
Is there any way to access the underlying cell's control from codebehind for RadDataGrid?
Alternative approach : Can we somehow user IsReadOnly property with some binding to check it's value and make the control readonly when value is there?
Can we somehow user IsReadOnly property with some binding to check it's value and make the control readonly when value is there?
Yes. You could certainly achieve this by using Binding. You just need to define a bool property and bind the IsReadOnly property of TextBox to this property. Then, you could change this bool value according to the text of TextBox.
Please refer to my following code sample for reference:
<telerikGrid:RadDataGrid x:Name="grid" AutoGenerateColumns="False" VerticalAlignment="Center">
<telerikGrid:RadDataGrid.Columns>
<telerikGrid:DataGridTemplateColumn Header="Country">
<telerikGrid:DataGridTemplateColumn.CellContentTemplate>
<DataTemplate>
<TextBox Text="{Binding Country}" HorizontalAlignment="Center" VerticalAlignment="Center" IsReadOnly="{Binding IsReadOnly}"/>
</DataTemplate>
</telerikGrid:DataGridTemplateColumn.CellContentTemplate>
</telerikGrid:DataGridTemplateColumn>
<telerikGrid:DataGridTemplateColumn Header="Flag">
<telerikGrid:DataGridTemplateColumn.CellContentTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Flag}" />
</StackPanel>
</DataTemplate>
</telerikGrid:DataGridTemplateColumn.CellContentTemplate>
</telerikGrid:DataGridTemplateColumn>
</telerikGrid:RadDataGrid.Columns>
</telerikGrid:RadDataGrid>
public sealed partial class MainPage : Page
{
ObservableCollection<Data> list = new ObservableCollection<Data>();
public MainPage()
{
this.InitializeComponent();
list.Add(new Data { Country = "Argentina",Flag="A"});
list.Add(new Data {Country=string.Empty,Flag="B"});
list.Add(new Data { Country = "China",Flag="C"});
this.grid.ItemsSource = list;
this.Loaded += MainPage_Loaded;
}
private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
await Task.Delay(5000);
list[1].Country = "Brazil";
}
}
public class Data:INotifyPropertyChanged
{
private string _Country;
public string Country
{
get { return _Country; }
set
{
_Country = value;
if (string.IsNullOrEmpty(value))
{
IsReadOnly = true;
}
else
{
IsReadOnly = false;
}
RaisePropertyChanged("Country");
}
}
private string _Flag;
public string Flag
{
get { return _Flag;}
set
{
_Flag = value;
RaisePropertyChanged("Flag");
}
}
private bool _IsReadOnly=false;
public bool IsReadOnly
{
get { return _IsReadOnly; }
set
{
_IsReadOnly = value;
RaisePropertyChanged("IsReadOnly");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,new PropertyChangedEventArgs(PropertyName));
}
}
}
I have a view that uses the SearchBox user control, The SearchBox has two radio buttons to select the search modes - Instant and delayed. I have binded the searchmodes to SearchMode property, and also I have created a custom dependency property for the Search Mode.
View
<controls:SearchBox Grid.Row="0"
HorizontalAlignment="Right"
Margin="2" Width="200"
SearchMode="{Binding DataContext.SearchMode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged }" />
ViewModel.cs
private Mode mSearchMode;
public Mode SearchMode
{
get
{
return mSearchMode;
}
set
{
mSearchMode = value;
NotifyOfPropertyChange();
}
}
// Called when application is restarted.
private void ActivateLastSelectedSearchMode(Mode lastselectedMode)
{
// Sets the last selected mode to the search mode
SearchMode = lastselectedMode;
}
public enum Mode
{
Instant,
Delayed,
}
SearchBox.xaml
<UserControl x:Class = "abc.SearchBox"
DataContext="{Binding RelativeSource={RelativeSource Self}}" >
<UserControl.Resources>
<converters:EnumToBooleanConverter x:Key="EnumToBooleanConverter" />
</UserControl.Resources>
<StackPanel Orientation="Vertical">
<RadioButton Content="{lex:Loc SearchBox:SearchModelInstatOption}"
IsChecked="{Binding Path=SearchMode, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static local:Mode.Instant}}" />
<RadioButton Content="{lex:Loc SearchBox:SearchModeDelayedOption}"
IsChecked="{Binding Path=SearchMode, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static local:Mode.Delayed}}" />
</StackPanel>
</UserControl>
SearchBox.xaml.cs
public partial class SearchBox : UserControl
{
public static DependencyProperty SearchModeProperty =
DependencyProperty.Register(
"SearchMode",
typeof(Mode),
typeof(SearchBox),
new FrameworkPropertyMetadata(default(Mode), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnIsSearchModeChanged));
static void OnIsSearchModeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var searchBox = obj as SearchBox;
searchBox.SearchMode = (Mode)e.NewValue;
}
public Mode SearchMode
{
get { return (Mode)GetValue(SearchModeProperty); }
set { SetValue(SearchModeProperty, value); }
}
}
I want the OnIsSearchModeChanged() to be fired each time when SearchMode is set during call back i e, ActivateLastSelectedSearchMode() is invoked in ViewModel.cs. I am absolutely clueless..where I am missing, I am unable to achieve success.
//snip
private Mode mSearchMode;
public Mode SearchMode
{
get
{
return mSearchMode;
}
set
{
mSearchMode = value;
NotifyOfPropertyChange(()=>SearchMode); //Change
}
}
does the reflected change make any difference? Other option would be to create a custom convention for your user control
You should create an Event in you View Model and subscribe to it from your code behind.
In your View Model :
public event SearchModeAction SearchModeChanged;
public delegate void SearchModeAction(object sender, EventArgs e);
public void SearchModeHasChanged()
{
SearchModeAction Handler = SearchModeChanged;
if (Handler != null)
{
Handler(this, null);
}
}
private void ActivateLastSelectedSearchMode(Mode lastselectedMode)
{
// Sets the last selected mode to the search mode
SearchMode = lastselectedMode;
SearchModeHasChanged()
}
In your Code Behind :
private void Window_Loaded(object sender, RoutedEventArgs e)
{
((YourViewModelClass)DataContext).SearchModeChanged += OnIsSearchModeChanged;
}
private void OnIsSearchModeChanged(object sender, EventArgs e)
{
var searchBox = obj as SearchBox;
searchBox.SearchMode = (Mode)e.NewValue;
}
This way each time you arrive in your ActivateLastSelectedSearchMode method in your View Model, you will call your OnIsSearchModeChanged method in your View.
Ahh..the reason was the EnumToBooleanConverter.
Though the value of 'parameter' and 'value' was same, There was a difference between their object types as both were referencing to different namespaces. So I created a public enum called 'Mode' and ensured that the 'Instant' and 'Delayed' reference to the same namespace.
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
{
return false;
}
return value.Equals(parameter); // This always returned false despite the values being the same
}
I have a ComboBox with some values, and I want to have two things working at once.
Here is my ComboBox and I want to show the 10 as default value and also to bind it to a double? Distance property.
<ComboBox Grid.Row="5" Grid.Column="1"
SelectedIndex="1"
SelectedValue="{Binding Distance, Mode=TwoWay, Converter={StaticResource StringToDoubleConverter}}">
<ComboBoxItem>1</ComboBoxItem>
<ComboBoxItem IsSelected="True">10</ComboBoxItem>
<ComboBoxItem>100</ComboBoxItem>
<ComboBoxItem>1000</ComboBoxItem>
</ComboBox>
And here is the converter:
public class StringToDoubleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
ComboBoxItem item = value as ComboBoxItem;
if (item != null)
{
double d;
if (double.TryParse(item.Content.ToString(), out d))
return d;
}
return null;
}
}
The problem is that in this code, The selected item 10 is not show at the start of the application.
If I will remove the line with the converter, then it will show the selected item 10, but then, I can't bind it to the double? Distance property. I dont want to write a code behind for it, such as: Convert.ToDouble(combobox1.SelectedValue)...
What can I do to make both things work?
You need to populate combo box items from ViewModel. Moreover you should not use SelectedValue property, instead of it you should use SelectedItem. See the below given code.
XAML
<ComboBox x:Name="cmb" ItemsSource="{Binding DistanceCollection}"
SelectedItem="{Binding Distance, Converter={StaticResource StringToDoubleConverter}, Mode=TwoWay}"/>
ViewModel
public class viewModel : INotifyPropertyChanged
{
public viewModel()
{
DistanceCollection = new ObservableCollection<string>
{
"1",
"10",
"100",
"1000"
};
Distance = double.Parse(DistanceCollection[1].ToString());
}
public ObservableCollection<string> DistanceCollection { get; set; }
private double _Distance;
public double Distance
{
get
{
return _Distance;
}
set
{
_Distance = value;
OnPropertyChanged("Distance");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName = null)
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Converter
public class StringToDoubleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
string item = value as string;
if (!string.IsNullOrWhiteSpace(item))
{
double d;
if (double.TryParse(item, out d))
return d;
}
return null;
}
}
I have a Silverlight DataGrid bound to a collection of MyObjects. MyObject has a boolean field called IsHighlighted.
I would like to change the row's background color when this value is true. And to have it changed back if it becomes false.
I already tried by using the Loading_Rowevent (as explained here), but it didn't work for me, as this event is only called once, and my objetcs all have the boolean value set to false at this time (it only becomes truc when another component is selectes; this works, I checked the values).
Anybody has a clue ? Thanks in advance !
Update: I made a test application to illustrate, it reproduces my problem.
<navigation:Page x:Class="AViews.Tests"
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:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
mc:Ignorable="d"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
d:DesignWidth="640" d:DesignHeight="480"
Title="Tests Page">
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<sdk:DataGrid Grid.Row="0" ItemsSource="{Binding AllItems, Mode=TwoWay}" AutoGenerateColumns="False" LoadingRow="DataGrid_LoadingRow">
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn Binding="{Binding Value1}" Header="Value1" />
<sdk:DataGridTextColumn Binding="{Binding Value2}" Header="Value2"/>
<sdk:DataGridCheckBoxColumn Binding="{Binding IsHighlighted}" Header="Is Highlighted" />
</sdk:DataGrid.Columns>
</sdk:DataGrid>
<Button Content="Change !" Grid.Row="1" HorizontalAlignment="Left" Click="Button_Click" />
</Grid>
</navigation:Page>
public partial class Tests : Page, INotifyPropertyChanged
{
private SampleConverter bgConverter = new SampleConverter();
Random r = new Random();
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
private ObservableCollection<Sample> allItemsField = new ObservableCollection<Sample>();
public ObservableCollection<Sample> AllItems
{
get
{
return this.allItemsField;
}
set
{
if (this.allItemsField != value)
{
this.allItemsField = value;
this.OnPropertyChanged("AllItems");
}
}
}
public Tests()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var tmp = Enumerable.Range(0, 100).Select(f => new Sample(f)).ToList();
foreach (var item in tmp)
{
item.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
}
var coll = new ObservableCollection<Sample>(tmp);
this.AllItems = coll;
}
void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
this.OnPropertyChanged("AllItems");
}
private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
Binding b = new Binding("IsHighlighted")
{
Mode = BindingMode.OneWay,
Converter = this.bgConverter,
ValidatesOnExceptions = true
};
e.Row.SetBinding(DataGridRow.BackgroundProperty, b);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
foreach (var item in this.AllItems)
{
item.IsHighlighted = r.Next(1000) % 2 == 0;
}
}
}
public class Sample: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
private string value1Field = string.Empty;
public string Value1
{
get
{
return this.value1Field;
}
set
{
if (this.value1Field != value)
{
this.value1Field = value;
this.OnPropertyChanged("Value1");
}
}
}
private string value2Field = string.Empty;
public string Value2
{
get
{
return this.value2Field;
}
set
{
if (this.value2Field != value)
{
this.value2Field = value;
this.OnPropertyChanged("Value2");
}
}
}
private bool isHighlightedField = false;
public bool IsHighlighted
{
get
{
return this.isHighlightedField;
}
set
{
if (this.isHighlightedField != value)
{
this.isHighlightedField = value;
this.OnPropertyChanged("IsHighlighted");
}
}
}
public Sample(int index)
{
this.Value1 = string.Format("Value1 #{0}", index);
this.Value2 = string.Format("Value2 #{0}", index);
}
}
public class SampleConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool val = (bool)value;
SolidColorBrush ret = val ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.Green);
return ret;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
And the result can be seen on those pictures:
When I first arrive on the page.
I click the button, which sets some (random) values to true. As you can see, the binding is updated, not the UI.
I use the scrollbar, go to the end, and come back, and Oh! wonderful! All the rows are correctly colored :-(