0

以前、単純な文字列リソースに静的クラスを使用した WinForms アプリケーションがありました。このクラスには、アクセスできる定数文字列がありました。これらの文字列の 1 つは、別の定数の値と独自の値で構成されていました。このようなもの:

private const string Path = @"C:\SomeFolder\";
public const string FileOne = Path + "FileOne.txt";
public const string FileTwo = Path + "FileTwo.txt";

現在、WPF アプリケーションがあり、Application スコープにマージした ResourceDictionary を使用しています。すべて正常に動作しますが、上記の C# コードのようなものが必要です。これは私がすでに持っているものです:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:System="clr-namespace:System;assembly=mscorlib">

    <System:String x:Key="Path">C:\SomeFolder\</System:String>
    <System:String x:Key="FileOne">FileOne.txt</System:String>
    <System:String x:Key="FileTwo">FileTwo.txt</System:String>

</ResourceDictionary>

ここで、2 つのファイル文字列に自動的に追加される何か (「パス」への何らかの参照) が必要です。C# コードのようにプライベートである必要はありません。どうすればこれを達成できるか知っている人はいますか?

前もって感謝します!

4

2 に答える 2

1

You can still use a static class with resources:

namespace WpfStaticResources
{
    class MyResources {
        private const string Path = @"C:\SomeFolder\";
        public const string FileOne = Path + "FileOne.txt";
        public const string FileTwo = Path + "FileTwo.txt";
    }
}

and then from your XAML reference that as:

<Window x:Class="WpfStaticResources.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:WpfStaticResources="clr-namespace:WpfStaticResources" 
    Title="{x:Static WpfStaticResources:MyResources.FileOne}" Height="350" Width="525">
    <Grid>

    </Grid>
</Window>

Personally I'd prefer to not use a static class, but instead create a domain object, set it as your DataContext and then bind to properties on it instead.

于 2012-09-25T15:16:23.640 に答える
1

XAML で使用する場合は、次の 2 つのアイデアがあります。

アイデア 1: 1 つBinding

リソースには、次のもののみを追加しPathます。

<System:String x:Key="Path">C:\SomeFolder\</System:String>

そして、XAML のどこかに:

<TextBlock Text='{Binding Source={StaticResource Path}, StringFormat={}{0}FileOne.txt}' />

これにより、パス+「FileOne.txt」が表示されます

(注: FileOne.txt の代わりに好きなものを書くことができます)

この方法を使用してカスタムのものを作成できます。

アイデア 2: 1 つMultiBinding

私見でやろうとしていることにより便利ですResources。定義した3つを保持します。

Path + fileOne が表示されるようにそれらをどこかで呼び出したい場合は、それを使用してください( の例TextBlock

    <TextBlock >
        <TextBlock.Text>
            <MultiBinding StringFormat="{}{0}{1}">
                <Binding Source="{StaticResource Path}" />
                <Binding Source="{StaticResource FileOne}" />
            </MultiBinding>
        </TextBlock.Text>
    </TextBlock>

それだけです!

または、UI でこれらの を使用しない場合Stringでも、静的クラスを使用できます。しかし、XAML の方法を使用する方がクリーンな印象です (UI 関連のものはすべて XAML に残す必要があります)。

于 2012-09-25T15:22:05.823 に答える