Storing a radio button selection in the settings - wpf

I've been looking at this article but am having issues saving the enumerated value in the settings.
I have created the following enum
public enum FType
{
None,
Delimited,
FixedWidth,
XML
};
I have the radio button selection working nicely but I now want to store the selected option in the settings but there doesn't appear to be the ability to store an enumerated variable.
I assumed I could convert the enum to a string and then convert back but being a bit of a noob when it comes to WPF I'm not realy sure where to start.
Here is the code I've generated so far:
App.Xaml
<Application x:Class="Widget.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:properties="clr-namespace:Widget.Properties"
StartupUri="Window1.xaml"
Exit="Application_Exit">
<Application.Resources>
<properties:Settings x:Key="Settings" />
</Application.Resources>
</Application>
App.xaml.cs
public partial class App : Application
{
private void Application_Exit(object sender, ExitEventArgs e)
{
Widget.Properties.Settings.Default.Save();
}
}
Windows.xaml
<Window x:Class="Widget.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Widget"
Title="Window1" Height="85" Width="300">
<Window.Resources>
<local:EnumBooleanConverter x:Key="enumBooleanConverter"/>
</Window.Resources>
<Grid>
<StackPanel>
<RadioButton GroupName="FileType" Content="Delimited" IsChecked="{Binding Path=Default.FileType, Mode=TwoWay, Converter={StaticResource enumBooleanConverter}, ConverterParameter=Delimited}" />
<RadioButton GroupName="FileType" Content="Fixed Width" IsChecked="{Binding Path=Default.FileType, Mode=TwoWay, Converter={StaticResource enumBooleanConverter}, ConverterParameter=FixedWidth}"/>
<RadioButton GroupName="FileType" Content="XML" IsChecked="{Binding Path=Default.FileType, Mode=TwoWay, Converter={StaticResource enumBooleanConverter}, ConverterParameter=XML}"/>
</StackPanel>
</Grid>
</Window>
Converter.cs
public class EnumBooleanConverter : IValueConverter
{
public EnumBooleanConverter()
{
}
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null)
return DependencyProperty.UnsetValue;
if (Enum.IsDefined(value.GetType(), value) == false)
return DependencyProperty.UnsetValue;
object parameterValue = Enum.Parse(value.GetType(), parameterString);
return parameterValue.Equals(value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string parameterString = parameter as string;
if (parameterString == null)
return DependencyProperty.UnsetValue;
return Enum.Parse(targetType, parameterString);
}
#endregion
}

Your code looks just fine, except 2 problems that I think may be preventing you from storing settings:
I think you should specify a DataContext for your RadioButtons. Just modify your Window1 like this:
<StackPanel DataContext="{StaticResource Settings}">
<RadioButton GroupName=... />
<RadioButton GroupName=... />
<RadioButton GroupName=... />
</StackPanel>
(Note: If StaticResource doesn't work try using DynamicResource)
Secondly, from your post it seems that you are storing values as string in settings. Just change this and instead set datatype of FileType to Ftype. (If you don't know how 2 do this, tell me)
After doing these 2 changes you'll surely get this working! I hope ;)

Related

How to assign the binding result to the ResourceKey of the DynamicResource?

I would like to switch an image dynamically following property value.
The image path is defined in the two ResourceDictory for the same key.
For this achieve, I wrote XAML code as below.
<HierarchicalDataTemplate DataType="{x:Type solutionPackage:ProjectStruct}" ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal">
<Image Width="16" Height="16" Margin="0 0 5 0"
Source="{Binding Extension, Converter={localConverters:ToResourceKeyConverter}, ConverterParameter='Extension'}"/>
<TextBlock Text="{Binding NameWithoutExtension}"/>
</StackPanel>
</HierarchicalDataTemplate>
The below code is Converter code.
class ToResourceKeyConverter : MarkupExtension, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return null;
if (parameter == null) return null;
if (parameter.ToString() == "Extension")
{
if (value.ToString() == ".mcproj")
return Application.Current.Resources["MCProjectImagePath"];
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
public override object ProvideValue(IServiceProvider serviceProvider) => this;
}
The below picture shows what the above code does.
MCProjectImagePath is defined in two ResourceDictory. one is DarkThemeImageResources.xaml and other is BasicImageResources.xaml.
Each code is as shown below.
In BasicImageResource.xaml
<BitmapImage x:Key="ProjectImagePath" UriSource="/Resources/Images/Basic/project.png"/>
<BitmapImage x:Key="MCProjectImagePath" UriSource="/Resources/Images/Basic/mcproject.png"/>
In DarkThemeImageResources.xaml
<BitmapImage x:Key="ProjectImagePath" UriSource="/Resources/Images/DarkTheme/project.png"/>
<BitmapImage x:Key="MCProjectImagePath" UriSource="/Resources/Images/DarkTheme/mcproject.png"/>
Please note it has the same key but UriSource value differs.
For now, the feature works well but does not switch the image when a user clicked some button.
So I thought I have to use DynamicResource keyword to switch dynamically so I changed the XAML code as below.
<HierarchicalDataTemplate DataType="{x:Type solutionPackage:ProjectStruct}" ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal">
<Image Width="16" Height="16" Margin="0 0 5 0"
Source="{DynamicResource ResourceKey={Binding Extension, Converter={localConverters:ToResourceKeyConverter}, ConverterParameter='Extension'}}"/>
<TextBlock Text="{Binding NameWithoutExtension}"/>
</StackPanel>
</HierarchicalDataTemplate>
My idea is the binding result is ResourceKey therefore, assign the binding result to the ResourceKey of the DynamicResource.
Compile works well but does not enter into the ToResourceKeyConverter code of the above so no image is displayed.
I would like to switch resources(ex:image) dynamically when a special button is clicked. the special button click action does not affect Extension property value. It just replaces ThemeDictory as below code.
private void OnOption()
{
// for test
var app = (App)Application.Current;
List<Uri> uris = new List<Uri>
{
new Uri("Resources/BasicImageResources.xaml", UriKind.RelativeOrAbsolute)
};
app.ChangeTheme(uris);
}
public void ChangeTheme(List<Uri> uris)
{
foreach (var uri in uris)
ThemeDictionary.MergedDictionaries.Add(new ResourceDictionary() { Source = uri });
var dictionary = ThemeDictionary.MergedDictionaries.ToList();
foreach(var item in dictionary)
{
if (uris.Contains(item.Source)) continue;
ThemeDictionary.MergedDictionaries.Remove(item);
}
}
Could someone tell me what I should do to solve this problem?
If you have a better way to solve this problem, please let me know.
I don't obsess in my way.
Thanks for reading.
You need to implement INotifyPropertyChanged interface to handle change notifications.
e.g.
class ProjectStruct : INotifyPropertyChanged
{
//......
//Your code
//......
private string extension;
public string Extension
{
get { return extension; }
set
{
extension = value;
// Call OnPropertyChanged whenever the property is updated
OnPropertyChanged("Extension");
}
}
.....
Interface implementation
.....
}
In xaml
<HierarchicalDataTemplate DataType="{x:Type solutionPackage:ProjectStruct}" ItemsSource="{Binding Children}">
<StackPanel Orientation = "Horizontal" >
<Image Width= "16" Height= "16" Margin= "0 0 5 0"
Source= "{Binding Extension Converter={localConverters:ToResourceKeyConverter} ConverterParameter='Extension' Mode=OneWay}"/>
<TextBlock Text= "{Binding NameWithoutExtension}" />
</StackPanel >
</HierarchicalDataTemplate >

Windows Phone Silverlight - setting button IsDisabled if bound data length is 0

Here's what I've got - I'm writing an App that, among other things, reads an RSS feed to get episodes of a certain podcast, then displays each episode's title and description, with a "listen" and "watch" button. But not all the episodes have both options - the RSS will return an empty string instead of a URL for either option if it's not available. So I'm trying to use IValueConverter that I can bind IsDisabled to, which returns true if the bound data length is 0, and false otherwise. For now, I'm just testing it on the "watch" buttons, since the binding will be nearly identical for the "listen" buttons.
A snippet of MainPage.xaml.cs:
using System.Xml.Linq;
using System.Windows.Data;
namespace appname
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
WebClient PodcastListDownloader = new WebClient();
PodcastListDownloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(PodcastListDownloadCompleted);
PodcastListDownloader.DownloadStringAsync(new Uri("http://domain.tld/mobile_app/podcastfeed"));
}
void PodcastListDownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
return;
XElement xmlPodcastList = XElement.Parse(e.Result);
PodcastListBox.ItemsSource = from PodcastEpisode in xmlPodcastList.Descendants("item")
select new PodcastItem
{
title = PodcastEpisode.Element("date").Value + " " + PodcastEpisode.Element("title").Value,
subtitle = PodcastEpisode.Element("subtitle").Value,
description = PodcastEpisode.Element("summary").Value,
audio = PodcastEpisode.Element("audio").Value,
video = PodcastEpisode.Element("video").Value,
};
}
private void PlayPodcast(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
Microsoft.Phone.Tasks.MediaPlayerLauncher PodcastPlay = new Microsoft.Phone.Tasks.MediaPlayerLauncher();
PodcastPlay.Media = new Uri(btn.Tag.ToString());
PodcastPlay.Show();
}
}
public class PodcastItem
{
public string title { get; set; }
public string description { get; set; }
public string audio { get; set; }
public string video { get; set; }
public string subtitle { get; set; }
}
public class StringLengthVisibilityConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null || value.ToString().Length == 0)
{
return false;
}
else
{
return true;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
A snippet of MainPage.xaml:
<phone:PhoneApplicationPage
x:Class="CCoFnow.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:controls="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="800"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="False">
<Grid x:Name="LayoutRoot" Background="Transparent">
<!--Panorama control-->
<controls:Panorama Title="AppName">
<controls:Panorama.Background>
<ImageBrush ImageSource="PanoramaBackground.png"/>
</controls:Panorama.Background>
<controls:PanoramaItem Header="Podcast" Foreground="{StaticResource PhoneAccentBrush}">
<ListBox Margin="0,0,-12,0" ItemsSource="{Binding Items}" Name="PodcastListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Width="432">
<TextBlock Text="{Binding title}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
<TextBlock Text="{Binding description}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
<StackPanel Orientation="Horizontal">
<Button Content="Listen" Width="215" Tag="{Binding audio}" Click="PlayPodcast"/>
<Button Content="Watch" Width="215" Tag="{Binding video}" Click="PlayPodcast" IsEnabled="{Binding video, Converter={StringLengthVisibilityConverter}}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</controls:PanoramaItem>
</controls:Panorama>
</Grid>
</phone:PhoneApplicationPage>
But the debugger is throwing two errors:
1) The tag
'StringLengthVisibilityConverter' does
not exist in XML namespace
'http://schemas.microsoft.com/winfx/2006/xaml/presentation
2) The type
'StringLengthVisibilityConverter' was
not found. Verify that you are not
missing an assembly and that all
referenced assemblies have been built
I set the converter to {StaticResource StringLengthVisibilityConverter} instead (per http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter(v=VS.95).aspx), and now there's just one error: The resource "StringLengthVisibilityConverter" could not be resolved. With this error, I can debug (run) the code, but all the "watch" buttons remain enabled.
So I'm guessing I'm calling it in the wrong namespace, but I can't seem to figure out the correct one. Can someone please point me in the right direction?
Thanks!
Edit: In the process of putting this together, I realized that I need to do this differently - the feed now has additional values I can databind to. However, I'm quite sure I'm going to need this functionality at some point in the future, so I'm going to post anyway. If there's an easy solution for the question, please let me know so I can learn and do it sucessfully next time!
The way you reference the converter isn't quite right. You need an instance of the converter available somwhere, e.g. in the page's Resources section:
<phone:PhoneApplicationPage xmlns:conv="namespace reference for your converter goes here"
...>
<phone:PhoneApplicationPage.Resources>
<conv:StringLengthVisibilityConverter x:Key="Length" />
</phone:PhoneApplicationPage.Resources>
Then you reference that converter by using a StaticResource reference with the x:Key that you gave the converter.
<Button Content="Watch"
Width="215"
Tag="{Binding video}"
Click="PlayPodcast"
IsEnabled="{Binding video, Converter={StaticResource Length}}"/>
I'll leave the discussion of your approach versus using commands and MVVM for another day :)

Silverlight: How to mantain the same localization for all countries

I need to know how to format a given number (or date, or whatever)
always italian language, no matter in what country the client is...
Example:
<TextBlock Text={Binding Price, StringFormat=C2} />
must return "€ 1.520,45" in every country is executed.
even if Italian language is not installed in that machine.
How can i achieve that?
(possibly is better if i can do it application wide)
Thanks in advance.
You can set the UICulture and Culture of the Silverlight application explicitly to ensure that regardless of the user locale the UICulture and Culture would be fixed.
This can be achieved in two ways
1- Set in the object tag on the browser
<param name="uiculture" value="it-IT" />
<param name="culture" value="it-IT" />
2- Set the thread culture in the Application_Startup
Thread.CurrentThread.CurrentCulture = new CultureInfo("it-IT");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("it-IT");
Update: The above does not seem to take effect when using StringFormat. Given this, I would revert to using a custom value converter. Below is a sample
MainPage.xaml
<UserControl x:Class="SLLocalizationTest.MainPage"
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:SLLocalizationTest"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<UserControl.Resources>
<local:DoubleToStringConverter x:Key="DoubleToStringConverter" />
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel>
<TextBlock Text="{Binding Price, Converter={StaticResource DoubleToStringConverter}, ConverterParameter=C2 }"/>
<TextBlock Text="{Binding Price, Converter={StaticResource DoubleToStringConverter} }"/>
</StackPanel>
</Grid>
</UserControl>
MainPage.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Globalization;
using System.Windows.Data;
namespace SLLocalizationTest
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
DataContext = this;
}
public double Price
{
get { return 12353.23; }
}
}
public class DoubleToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value is double)
{
return ((double)value).ToString((string)parameter);
}
return value.ToString();
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}

Binding in WPF to element of array specified by property

Say I've got some TextBlocks on my UI, something like so:
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding DessertIndex}" />
<TextBlock Text="{Binding Food[2]}" />
<TextBlock Text="{Binding Food[{Binding DessertIndex}]}" />
</StackPanel>
and in my code behind I've got something like this:
public partial class MainWindow : Window
{
public int DessertIndex
{
get { return 2; }
}
public object[] Food
{
get
{
return new object[]{"liver", "spam", "cake", "garlic" };
}
}
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
}
The first two TextBlocks display fine for me, displaying 2 and 'cake' respectively. The third one doesn't accomplish what I'd like, namely use the DessertIndex property to index into that array and also display 'cake'. I did a little searching here on SO for a similar question but didn't find one. Ultimately, I don't want to specify values like 2 in my .xaml file and would like to rely upon a property instead for indexing into that array. Is this possible? If so, what am I doing wrong here?
EDIT:
So what I more closely have is a situation where the data is a List of these object[] and I'm using the above StackPanel as part of a DataTemplate for a ListBox. So the idea, as Mark Heath suggests below, of using a property that dereferences the array doesn't seem to work as I'd want. Ideas?
Another alternative is to use MultiBinding with a converter:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<StackPanel Orientation="Vertical">
<StackPanel.Resources>
<local:FoodIndexConverter x:Key="foodIndexConverter" />
</StackPanel.Resources>
<TextBlock Text="{Binding DessertIndex}" />
<TextBlock Text="{Binding Food[2]}" />
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource foodIndexConverter}">
<Binding Path="DessertIndex" />
<Binding Path="Food"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</StackPanel>
</Window>
Then in the code-behind, the converter is defined something like this:
namespace WpfApplication1
{
public class FoodIndexConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (values == null || values.Length != 2)
return null;
int? idx = values[0] as int?;
object[] food = values[1] as object[];
if (!idx.HasValue || food == null)
return null;
return food[idx.Value];
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
if you are going to the trouble of having a DesertIndex property on your DataContext, why not a property that dereferences the Food array with DesertIndex:
public object SelectedFood
{
get { return Food[DessertIndex]; }
}
public int DessertIndex
{
get { return 2; }
}
public object[] Food
{
get
{
return new object[]{"liver", "spam", "cake", "garlic" };
}
}
then you can bind directly to that:
<TextBlock Text="{Binding SelectedFood}" />
This is essentially the "MVVM" approach: make the datacontext object have properties that are just right for binding to.
Just To add on the great answer by Colin Thomsen.
You could also use C# dynamic keyword to make this solution work with pretty much every container type. Or even bind to multidimensional containers "{Binding Food[{Binding DessertIndex1}][{Binding DessertIndex2}]}"
public class ContainerDoubleAccessConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
try
{
dynamic idx1 = values[0];
dynamic idx2 = values[1];
dynamic container = values[2];
return container[idx1][idx2];
}
catch (System.Exception err)
{
DebugTrace.Trace("bad conversion " + err.Message);
}
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}

Binding WPF ComboBox to List<MyClass> where MyClass doesn't have properties, just methods

I want to bind a combo box to a list of Device, List. I use,
m_ctrlCB.DataContext = m_List;
m_ctrlCB.DisplayMemberPath = "ToString()";
m_ctrlCB.SelectedValuePath = "ToString()"; // do I even need this?
I don't have any properties in Device to bind to and it's not my class. However, they do override ToString to something that is suitable for displaying in the combobox (something like: "Class Device. Number 1".
However, what I wrote doesn't work. What I see in the combobox is blank items. My selectionChanged event does work AND e.AddedItems[0] really is a Device, so I'm close. How can I get something meaningful to display in the combox box.
I suppose I'd also be happy creating ComboBoxItems and adding them to the ComboBox if necessary. But if I go this route, how do I set the Display stuff and the actual object itself so I can get it when the user selects it from the combobox?
Bonus question. If instead of using ToString, I want to use GetDeviceNumber() and combine it with my own test so the user sees,
Device #1
Device #2
how would I do this?
thanks,
Dave
You don't have to set the DisplayMemberPath and the SelectedValuePath. Since your Device object overrides ToString(), it should display the correct string on its own.
EDIT:
To answer your "bonus question", one way to do this is to use an IValueConverter that calls the method you're interested in. The sample code below demonstrates this. I have here a combobox whose items are represented by a TextBlock (which shows the value for the ToString() method), as well as a Button (which shows the value for the GetDeviceNumber() method).
XAML:
<Window x:Class="StackOverflow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:StackOverflow"
Title="MainWindow" Height="350" Width="525"
x:Name="window">
<ComboBox x:Name="cb">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding}"/>
<Button>
<Button.Content>
<Binding>
<Binding.Converter>
<local:DeviceValueConverter/>
</Binding.Converter>
</Binding>
</Button.Content>
</Button>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Window>
Code-Behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.cb.ItemsSource = new List<Device>()
{
new Device("Device1"),
new Device("Device2"),
new Device("Device3"),
};
}
}
public class Device
{
private string text;
public Device(string text)
{
this.text = text;
}
public string GetDeviceNumber() { return this.GetHashCode().ToString(); }
public override string ToString() { return this.text; }
}
public class DeviceValueConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is Device)
{
return (value as Device).GetDeviceNumber();
}
return string.Empty;
}
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new System.NotImplementedException();
}
#endregion
}
One way you could do it would be to create a wrapper class and provide the appropriate properties on it. For example:
class DeviceWrapper
{
private Device device;
public DeviceWrapper(Device device)
{
this.device = device;
}
public int DeviceNumber
{
return this.device.GetDeviceNumber();
}
// etc...
}
You should try to use ObjectDataProvider.
It will be something like this
...
<UserControl.Resources>
<ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type sys:Enum}"
x:Key="AlignmentValues">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="HorizontalAlignment" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</UserControl.Resources>
<Border Margin="10" BorderBrush="Aqua"
BorderThickness="3" Padding="8">
<StackPanel Width="300">
<TextBlock>bla-bla</TextBlock>
<ListBox Name="myComboBox" SelectedIndex="0" Margin="8"
ItemsSource="{Binding Source={StaticResource AlignmentValues}}"/>
<Button Content="Click Me!"
HorizontalAlignment="{Binding ElementName=myComboBox,
Path=SelectedItem}"/>
</StackPanel>
</Border>
...

Resources