2014-09-04 116 views
1

我有一個靜態只讀變量存儲從運行時獲得的文件路徑。我想從這個靜態只讀變量中加載spellcheck.customdictionaries uri,我該怎麼做?我已與指定的XAML文件的完整路徑工作:如何從xaml使用x指定構造函數參數:static

<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> 

我想要讓這個開放的我們得到它在運行時從一個靜態變量的值。我想在xaml中完成,而不是從後面的代碼中完成。

回答

0

x:Arguments來指定構造函數參數,但我不認爲這適用(根據this answer)。

也許最簡單的方法來從XAML做到這一點將是寫一個Behavior<TextBox>。這可能會提供一個「URL」參數,這樣就可以使用這樣的:

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

當然你也可以通過使「URL」的附加屬性,該屬性附加/分離的行爲,這樣可以讓你進一步簡化簡單地寫:

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

行爲的代碼應該是這個樣子:

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)); 
    } 
} 
相關問題