Hide button when label is not empty - c#

I am using WPF.
I want to show button when the label is not empty. When Label has a value, the button will be hidden.
How can I do this with WPF? Using <Style>?
Code:
<Label Name="lblCustomerName"/>
<Button Name="btnCustomer" Content="X" Visibility="Hidden" />

try
if (string.IsNullOrEmpty(lblCustomerName.Text)) {
btnCustomer.Visibility = Visibility.Hidden;
}
else {
btnCustomer.Visibility = Visibility.Visible;
}

You will need to use a converter and bind it to the content of lblCustomer.
public class ContentNullToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return Visibility.Hidden;
}
return Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
More on converters here.
Then in xaml you can do the following:
First line needs to be defined in your resources where you will need to qualify it with the namespace in which you created the class above. Once you have defined the resource you can use the second part.
<ContentNullToVisibilityConverter x:Key="visConverter"/>
<Label Name="lblCustomerName"/>
<Button Name="btnCustomer" Content="X" Visibility="{Binding ElementName=lblCustomer, Path=Content, Converter={StaticResource visConverter}}" />

Related

`IsChecked` Binding Fails for no Apparent Reason

I’m trying to learn XAML (without much success) – be gentle.
I have a toggle button, a slider and a button. This is what I am trying to do:
When the slider’s value is changed the toggle button should turn off – works fine.
When the button is pressed, set the slider value and keep the toggle button in whichever state it is – does not work; after I push the button, (1) does not work anymore. It behaves like the IsChecked binding was cleared.
Ideally I would like to write everything in XAML, but I guess it is not possible.
// MainWindow.xaml.cs
public class ValueToFalse : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var saved = toggle.IsChecked;
slider.Value = 2;
toggle.IsChecked = saved;
}
}
<!--App.xaml-->
<local:ValueToFalse x:Key="ValueToFalse"/>
<!--MainWindow.xaml-->
<ToggleButton
Name="toggle"
Content="toggle"
HorizontalAlignment="Left"
Margin="479,64,0,0"
VerticalAlignment="Top"
Height="108"
Width="192"
IsChecked="{Binding Value, Mode=OneWay, ElementName=slider, Converter={StaticResource ValueToFalse} }"
/>
<Slider
Name="slider"
HorizontalAlignment="Left"
Margin="167,105,0,0"
VerticalAlignment="Top"
Width="233"
Height="35"
/>
<Button
Content="Button"
HorizontalAlignment="Left"
Margin="346,340,0,0"
VerticalAlignment="Top"
Click="Button_Click"
/>
I didn't quite understand what you want to implement.
But nevertheless, you have an obvious mistake that #Clemens pointed out - if you need to assign a Dependency Property value and keep the binding from it, then the binding must be in the direction of the TwoWay or OneWaySource source.
Since you do not need to assign a value to the source, but you need to store the direction to the source in the binding, you can solve this by implementing a converter.
I show the full implementation of the converter with markup extension. This may be useful to you in the future.
[ValueConversion(typeof(object), typeof(bool))]
public class ValueToFalseConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// This value tells the binding that the result of the conversion should not be assigned.
return Binding.DoNothing;
}
private ValueToFalseConverter() { }
public static ValueToFalseConverter Instance { get; } = new ValueToFalseConverter();
}
[MarkupExtensionReturnType(typeof(ValueToFalseConverter))]
public class ValueToFalseExtension : MarkupExtension
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
return ValueToFalseConverter.Instance ;
}
}
<ToggleButton
----------
----------
IsChecked="{Binding Value,
Mode=TwoWay,
ElementName=slider,
Converter={local:ValueToFalse}}"
/>

Xamarin Persistent color chooser

I make a button and Color picker to xamarin.forms app, but I want to make it when I choose one color (ex. red) and close app, when i reopen it to see this red color automatic picked. I try to use this code but Preferences not working with Color:
public Color ColorPicker
{
get => Preferences.Get(nameof(ColorPicker), color.Red);
set
{
Preferences.Set(nameof(ColorPicker), value);
OnPropertyChanged(nameof(ColorPicker));
}
}
Can someone help me?
You can store Xamarin.Forms.Color as a string like this:
public string ColorPicker
{
get => Preferences.Get(nameof(ColorPicker), Color.Red.ToString());
set
{
Preferences.Set(nameof(ColorPicker), value);
OnPropertyChanged(nameof(ColorPicker));
}
}
Then you can bind it for instance to Label like this:
<Label TextColor="{Binding ColorPicker}" />
Make sure you set BindingContext in your view. You can read more about Binding here.
The Color.FromHex(string value) method needs a string type parameter. Try to convert the value to string type in the custom class.
Check the code:
Custom Converter class
public class StringToColorConverter : IValueConverter, INotifyPropertyChanged
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var color = Color.FromHex(value as string);
return color;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Page.xaml
<ContentPage.Resources>
<local:StringToColorConverter x:Key="myConverter" />
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout BackgroundColor="{Binding Color_string, Converter={StaticResource myConverter}}">
...
</StackLayout>
</ContentPage.Content>
I is not possible to make it like this. Because i need to use converter after to make string=>color. I am trying this:
public class StringToColor : IValueConverter
{
ColorTypeConverter converter = new ColorTypeConverter();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
//return value.ToString(); //not working
//return (Color)(converter.ConvertFromInvariantString(value.ToString())); //not working
return Color.FromHex(value.ToString()); //not working too
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
and add this convetor to xaml
<ContentPage.Resources>
<ResourceDictionary>
<local:StringToColor x:Key="str" />
</ResourceDictionary>
</ContentPage.Resources>
<Label Text="TEST" FontSize="Title" TextColor="{Binding ColorPicker,
Converter={StaticResource str}}"/>
but nothing happend...

NullToVisibilityConverter make visible if not null

Want to hide and show property grid for SelectedItem in listview
<UserControl xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
<ListView>
<!--here is list view-->
</ListView>
<xctk:PropertyGrid SelectedObject="{Binding Active}" Visibility="{Binding Active, Converter=NullToVisibilityConverter}" >
</xctk:PropertyGrid>
</UserControl>
So I need converter and use it in visibility property converter. Any help?
public class NullVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? Visibility.Hidden : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Then reference the NullVisibilityConverter in your XAML Resources.
<StackPanel.Resources>
<simpleXamlContent:NullVisibilityConverter x:Key="NullToVisibilityConverter"/>
</StackPanel.Resources>
To use the converter we can create one in the resources, and refer to it as a static resource in the binding statement.
<UserControl xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit">
<UserControl.Resources>
<yournamespace:NullVisibilityConverter x:Key="NullToVisibilityConverter"/>
</UserControl.Resources>
<ListView>
<!--here is list view-->
</ListView>
<xctk:PropertyGrid SelectedObject="{Binding Active}" Visibility="{Binding Active, Converter={StaticResource NullToVisibilityConverter}}" >
</xctk:PropertyGrid>
</UserControl>
and Converter class itself
public class NullVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? Visibility.Hidden : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
There is little more useful version allows to set default invisibility value:
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string defaultInvisibility = parameter as string;
Visibility invisibility = (defaultInvisibility != null) ?
(Visibility)Enum.Parse(typeof(Visibility), defaultInvisibility)
: Visibility.Collapsed;
return value == null ? invisibility : Visibility.Visible;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return DependencyProperty.UnsetValue;
}
Where ever in resources add:
<converters:NullReferenceToVisibilityConverter x:Key="NullToVis" />
And use it like there:
<StackPanel Visibility="{Binding MyObject, Converter={StaticResource NullToVis}}">
<StackPanel Visibility="{Binding MyObject, Converter={StaticResource NullToVis}, ConverterParameter=Hidden}">

How can we handle Null Values while Binding data to Text block in Windows phone

Hear i Have a confusion while Binding the data to Text Block in Windows phone
I have Text Block
<TextBlock Name="strytxt"
Text="{Binding STORY}"
Height="auto"
Width="Auto"
TextWrapping="Wrap"/>
in STORY Object some time I have Empty/Null Values
At that Time im Getting Some space in my UI
Now i Want to Make Visibility of the Textbox in to Collapsed if i get Null in that row
How can i do this
To change the Visibility of the TextBlock when the Binding value is null you need to use a Converter that converts from null/not null to Visible/Collapsed.
Here´s a converter that converts the values. The converter handles an empty string as null, so that it return Collapsed for string.empty.:
public class NullToVisibilityConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
bool isVisible = value == null ? false : true;
if (isVisible) {
string stringValue = value as string;
if (stringValue != null) {
isVisible = string.IsNullOrEmpty(stringValue) ? false : true;
}
}
if (System.ComponentModel.DesignerProperties.IsInDesignTool) {
return Visibility.Visible;
}
return isVisible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
You can apply the converter to the TextBlock as follows:
<UserControl.Resources>
<local:NullToVisibilityConverter x:Key="NullToVisibilityConverter"/>
</userControl.Resources>
<TextBlock Name="strytxt"
Visibility="{Binding STORY, Converter={StaticResource nullToVisibilityConverter}}"/>
Another alternativ is to display a Text when the value is null, you can specify that in the binding
<TextBlock Name="strytxt"
Text="{Binding STORY, TargetNullValue='is Null'}"/>
You can use a value converter to convert the value to a visibility:
public class NullToVisibiltyConverter : IValueConverter {
public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture) {
return value == null ? Visibility.Collapsed : Visibility.Visible;
}
public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
You then bind the Visibility of the TextBlock using the converter:
<TextBlock Name="strytxt"
Text="{Binding STORY}"
Height="auto"
Width="Auto"
TextWrapping="Wrap"
Visibility="{Binding STORY, Converter={StaticResource NullToVisibilityConverter}}"/>
You need to add an instance of the converter to a resource dictionary to be able to reference it in the binding:
<UserControl.Resources>
<local:NullToVisibilityConverter x:Key="NullToVisibilityConverter"/>
</userControl.Resources>

Make converter for columnSpan

I would like to dynamic do the columnSpan on the userControl. I created the converter class, but it didn’t work. Would you show me how to do it correctly? Thanks.
The code on my UserControl:
<TextBlock x:Name="txtSumary" Grid.Row="0" Grid.Column="1" Text="{Binding summary}"
TextWrapping="Wrap" Style="{StaticResource PhoneTextAccentStyle}" Grid.ColumnSpan="{Binding isSpan, Converter={StaticResource ColumSpanConverter}}" />
It is reference on the UserControl.Resources
<local:VisibilityConverter x:Key="ColumSpanConverter"/>
There is the Converter Class:
public class ColumSpanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
bool isSpan = (bool)value;
return isSpan ? 2 : 0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
The converter is referencing the wrong converter:
<local:VisibilityConverter x:Key="ColumSpanConverter"/>
Should be:
<local:ColumSpanConverter x:Key="ColumSpanConverter" />

Categories