1

I have a static readonly variable storing a file path that I get from runtime. I want to load the spellcheck.customdictionaries uri from this static readonly variable, how do I do it? I have made it work with specifying the full path of the file in xaml:

<TextBox Name="txtNote"
             Grid.Column="0"
             AcceptsReturn="True"
             MaxLines="2"
             VerticalScrollBarVisibility="Auto"
             Text="{Binding Path=Note,
                            ElementName=ucNoteEditor}"
             TextWrapping="WrapWithOverflow" SpellCheck.IsEnabled="True" >

        <SpellCheck.CustomDictionaries>
            <sys:Uri>m:\test.lex</sys:Uri>
        </SpellCheck.CustomDictionaries>
    </TextBox>

I want to make it so that the Uri get it's value from a static variable at runtime. I want to do it at the xaml, not from code behind.

Etheryte
  • 24,589
  • 11
  • 71
  • 116
gavin
  • 1,276
  • 1
  • 11
  • 17

1 Answers1

0

There is x:Arguments to specify constructor arguments, but I don't think that applies (per this answer).

Probably the easiest way to do this from XAML would be to write a Behavior<TextBox>. That could provide a "Url" parameter, so that you could use it like this:

<TextBox ...>
    <i:Interaction.Behaviors>
        <local:CustomDictionaryBehavior Url="{StaticResource SomeKey}" />
    </i:Interaction.Behaviors>
</TextBox>

You can of course simplify further by making "Url" an attached property which attaches/detaches the behavior, which would allow you to write simply:

<TextBox ... local:CustomDictionaryBehavior.Url="{StaticResource SomeKey}" />

The behavior code should look something like this:

public class CustomDictionaryBehavior : Behavior<TextBox>
{
    public static string GetUrl(DependencyObject obj)
    {
        return (string)obj.GetValue(UrlProperty);
    }

    public static void SetUrl(DependencyObject obj, string value)
    {
        obj.SetValue(UrlProperty, value);
    }

    public static readonly DependencyProperty UrlProperty =
        DependencyProperty.RegisterAttached("Url", typeof(string), typeof(CustomDictionaryBehavior), new PropertyMetadata((sender, args) => {
            Interaction.GetBehaviors(sender).Add(new CustomDictionaryBehavior());
        }));

    protected override void OnAttached()
    {
        string url = GetUrl(AssociatedObject);
        AssociatedObject.CustomDictionaries.Add(new Uri(url));
    }
}
Community
  • 1
  • 1
McGarnagle
  • 101,349
  • 31
  • 229
  • 260