I want to bind Value of a Slider to a Content of a Label. The value of the slider sets a timespan. The value of the slider is a timespan in minutes (value 5 = 5 minutes).
This is my XAML for the Label:
<Label
Content="{Binding Value, ElementName=sld_Timespan}"
ContentStringFormat="{}{0:HH:mm}"
/>
I can bind them. The values are correct. But the format is wrong.
For ContentStringFormat i tried different settings, like on this (TextBlock in Silverlight) or this (TextBlock Multibinding) site. I also took the data binding dialog and set the StringFormat to {0:G} (you can choose this from a ComboBox) or other settings.
I only get a value "formatted" as double, like "1" or "13.423523423".
I also tried TextBlock. The same problem.
What is wrong with my XAML code?
After the comment of Clemens i understood what was wrong. I wrote a simple Converter:
public class DoubleToTimespanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return TimeSpan.FromMinutes((double)value).ToString(#"hh\:mm\:ss");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
And added to my XAML:
<UserControl.Resources>
<!--local is my local namespace-->
<local:DoubleToTimespanConverter x:Key="converter"/>
</UserControl.Resources>
And i could easily set "converter" as my converter.
Related
I use FFImageLoading to show SVG images in a ListView like this :
1) I have an XML file with categories and items, I parse it, I have an ObservableCollection, each Category is an ObservableCollection.
2) I have a custom TintedSvgCachedImage class which inherits from SvgCachedImage (just adding some tint color on a bindable property) ; I bind the Source property to a a Category.Label property, and use a converter to return an SvgImageSource.
3) If the corresponding embedded resource is not found, I catch the Exception and I return another image.
This works very well when the image is found. When not, I face 2 issues :
1) If it is the last Category in the ListView, no Exception is thrown and the images is just "empty", nothing is displayed, without any error
2) If it is not the last Category, an Exception is thrown as expected, but the replacing image is not the one I wanted to load !
My XAML file :
<ListView.GroupHeaderTemplate>
<DataTemplate x:DataType="models:Category">
<ViewCell Height="50">
<StackLayout Orientation="Horizontal">
<ffsvgimg:TintedSvgCachedImage Source="{Binding Label, Converter={StaticResource CategoryNameToSvgImageResource}}"
TintColor="Accent" />
<Label Text="{Binding Name, Converter={StaticResource StringCaseConverter}, ConverterParameter=U}"
Padding="15, 0" VerticalOptions="CenterAndExpand"
FontSize="12" FontAttributes="Bold" Opacity="0.75" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
And the converter :
// Convert Category Name (or Label) to SVG image resource to be displayed in ListView
public class CategoryNameToSvgImageResourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value.GetType() != typeof(string))
throw new FormatException("CategoryNameToSvgImageResource: argument value is not of type String.");
try
{
return SvgImageSource.FromResource("CardioCALC.Resources." + value.ToString() + ".svg");
}
catch (Exception)
{
return SvgImageSource.FromResource("CardioCALC.Resources.HeartFailure.svg");
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
Does the problem come from me ? Missing something ?
Or do I have to open an issue on GitHub ? (I did not find any, but I did not search a lot as I am not sure the problem is not my bad...)
Thanks,
Olivier
I have a slider with maximum value of video's time in seconds (1 minute = 60 seconds, so if the video is 60 seconds length, the maximum value of the slider will be 60).
When I drag the Thumb, there's ThumbTooltip that shows the current value I am hovering.
I want to change that text so instead of displaying int, it will display time 1 will be 00:01 and so on...
I tried to play with the style of the Slider with no luck.
Will appreciate your help.
Slider has ThumbToolTipValueConverter property. You need to create class which implements IValueConverter interface. In that the Convert method will help you to convert the default slider value to your customized value. See the below code.
XAML
<Page.Resources>
<local:SliderValueConverter x:Key="SliderValueConverter"/>
</Page.Resources>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Slider Maximum="60" Value="40" Height="100" Width="300" ThumbToolTipValueConverter="{StaticResource SliderValueConverter}" />
</Grid>
SliderValueConverter.cs
public class SliderValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var seconds = System.Convert.ToInt32(value);
return string.Format("{0:00}:{1:00}", (seconds / 60) % 60, seconds % 60);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
I am developing an Windows Store app using C# and XAML and am working on a user input page. I use an IValueConverter that converts my bound data into currency formatted string instead of just showing a decimal.
When the user navigates to the page, the converter works fine and the TextBox text shows up with a currency format. However, when the user changes the TextBox.Text value and then the TextBox loses focus, the converter does not change it into a nice currency format again, it just stays formatted as it was entered by the user.
As far as I can tell, there is no StringFormat to use like in WPF, so how do I get the TextBox to display the currency format again after the user edits the value?
My converter:
public object Convert(object value, Type targetType, object parameter, string language)
{
if (parameter == null)
return ((decimal)value).ToString();
return String.Format((string)parameter, (decimal)value);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
decimal decVal = 0M;
decimal.TryParse((string)value, out decVal);
return decVal;
}
My XAML:
<Grid x:Name="InputGrid">
...
<Border>
<TextBox Text="{Binding MyValue, ConverterParameter='{}{0:c}', Converter={StaticResource DecimalValueConverter}, Mode=TwoWay}"
</Border>
....
</Grid>
InputGrid.DataContext = MyValueClassInstance set in the code-behind
Does your converter work both ways? I suspect that if it doesn't - the TwoWay binding gets broken.
What if you do this:
<TextBox Text="{Binding MyValue, UpdateSourceTrigger=PropertyChanged, ConverterParameter='{}{0:c}', Converter={StaticResource DecimalValueConverter}, Mode=TwoWay}"
I have objects stored in a database that I am displaying in a GridView. I am binding each of their properties from the database. The color property is stored as a Hex value.
I am trying to bind this hex value using a converter function as shown below and just returning Red every time for now.
It seems to be working but it eventually returns the following error:
The program '[5548] TranslatorService.Example.exe: Managed (v4.0.30319)' has exited with code -1073741189 (0xc000027b).
Can anyone tell me what I am doing wrong?
The code-behind:
public class StringToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, String language)
{
return Colors.Red;
}
public object ConvertBack(object value, Type targetType, object parameter, String language)
{
throw new NotImplementedException();
}
}
The XAML:
<Grid.Background>
<SolidColorBrush Color="{Binding Path=ColorHex, Converter={StaticResource ColorConverter}}" />
</Grid.Background>
Thank you
In my experience you need to assing a Brush, not a Color:
SolidColorBrush mySolidColorBrush = new SolidColorBrush();
mySolidColorBrush.Color = Color.FromArgb(255, 255, 0, 0);
or
mySolidColorBrush.Color = Color.Red;
The problem seems to be resolved after recompiling.
In your posted converter code, you are returning Color.Red, so no matter what value is, you'll get Red every time.
I am trying to pass the ListView or the GridView as a ConverterParameter
However, in the Converter routine the parameter is coming as a type string
Below is the part of the XAML List view and the Converter class.
Any help greatly appreciated. Thanks!!!
<ListView Name="SeqDtStDataListView1" Grid.Row="1"
DataContext="{Binding Path=DisplayDT[0], Converter ={StaticResource
CNVToColumn},ConverterParameter=?????}"
VerticalContentAlignment="Stretch" VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
SelectionChanged="SEQDatalistview_SelectionChanged" Margin="5">
<ListView.View >
<GridView x:Name="SeqDtStDataGridView1"/>
</ListView.View>
</ListView>
Converter:
namespace MFTest.Converters
{
public class CNVToColumn : IValueConverter
{
public object Convert(object value,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
DataTable dt = (DataTable)value;
GridView GV = (GridView)parameter; <========= fail here ===========
if (dt != null && GV != null)
foreach (var colum in dt.Columns) // Binding the Columns
{
DataColumn dc = (DataColumn)colum;
GridViewColumn column = new GridViewColumn();
column.DisplayMemberBinding = new Binding(dc.ColumnName);
column.Header = dc.ColumnName;
GV.Columns.Add(column);
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
From .NET 4 onwards you could use x:Reference which allows you to avoid a ElementName binding which can only be set on dependency properties while achieving pretty much the same thing.
Due to cyclical dependency restrictions you cannot reference a control inside itself or its ancestors in the tree. You can however move the binding up a level and just inherit the DataContext, e.g.
<Border DataContext="{Binding Path=DisplayDT[0],
Converter={StaticResource CNVToColumn},
ConverterParameter={x:Reference SeqDtStDataListView1}}">
<ListView Name="SeqDtStDataListView1" Grid.Row="1">
You can't bind to it.
ConvertParameter inherits from Object and therefore is not bindable.
You can, however, define your Binding in the code behind instead of doing it in the XAML part.
System.Windows.Data.Binding b = new System.Windows.Data.Binding();
b.ConverterParameter = this;
Please read about the limitations on the ConvertParameter here
You could use ConverterParameter={Binding ElementName=[insert x:Name of grid view]}
Although IMHO I'd reconsider the need - do you really need to pass a UIControl as a Converter parameter?