views:

69

answers:

2

Hi, I'm trying to set the selected value of my Font Family combobox, which has been populated with the following XAML:

<ComboBox ItemsSource="{x:Static Fonts.SystemFontFamilies}" Name="cboFont">
    <ComboBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel MinWidth="256" />
        </ItemsPanelTemplate>
    </ComboBox.ItemsPanel>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Margin="2" Text="{Binding}" FontFamily="{Binding}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

The field I have to set the combobox to is a string, but that causes FormatExceptions. Can anyone quickly tell me what class the combobox will be expecting and also how to convert a string e.g. "Arial" to that format?

+3  A: 

Hope I've understood your question correctly.

FontFamily supports the constructor

FontFamily(String familyName);

So you should be able to use something like new FontFamily("Arial") to convert from a string to a FontFamily.

You could put that in a class which implements IValueConverter which converts between FontFamily and String.

To get from FontFamily to string, you can access the FamilyNames property to get a name for the font which is specific to a particular culture.

Then just set your FontFamily binding to use the converter.

Alex Humphrey
That's exactly what I wanted, thanks. I won't be able to try it for 10 hours or so, when I hope to be able to mark this as the answer
Nick Udell
Worked perfectly. Thanks.
Nick Udell
+1  A: 

Alex' answer sounds very good.

You could also try a DependencyProperty:

   public FontFamily FontFamily
        {
            get { return (FontFamily)GetValue(FontFamilyProperty); }
            set { SetValue(FontFamilyProperty, value); }
        }

 public static DependencyProperty FontFamilyProperty =
            DependencyProperty.Register(
            "FontFamily",
            typeof(FontFamily),
            typeof(YourClassVM),
             new FrameworkPropertyMetadata(SystemFonts.MessageFontFamily
        , FrameworkPropertyMetadataOptions.AffectsRender |
        FrameworkPropertyMetadataOptions.AffectsMeasure)
            );

Then you simply bind the SelectedItem of your Combobox and the Text and FontFamily of your TextBlock to "FontFamily".

Torsten