programing

WPF 코드 배후에 의한 리소스 액세스

elseif 2023. 4. 9. 21:08

WPF 코드 배후에 의한 리소스 액세스

창 리소스에 다음과 같이 정의된 사용자 지정 컬렉션이 있습니다(Sketchflow 앱에서 창은 실제로 UserControl이 됩니다).

<UserControl.Resources>
    <ds:MyCollection x:Key="myKey" x:Name="myName" />
</UserControl.Resources>

코드 배후에 있는 이 컬렉션을 참조할 수 있도록 하고 싶습니다.이 컬렉션은 x:Name이라고 생각했지만 액세스 할 수 없는 것 같습니다.

다음을 사용하여 참조할 수 있습니다.

myRef = (MyCollection) this.FindName("myKey");

하지만 이건 해킹한 것 같아.이것은 나쁜 관행이며, 어떤 것이 더 좋을까요?감사합니다:)

를 사용해 주세요.System.Windows.Controls.UserControlFindResource()또는TryFindResource()방법들.

또한 리소스 사전에서 키 이름을 매핑하는 문자열 상수를 만드는 것이 좋습니다(이렇게 하면 한 곳에서만 키를 변경할 수 있습니다).

를 사용할 수도 있습니다.this.Resources["mykey"]그건 당신 자신의 제안보다 별로 낫지 않은 것 같아요.

정확히는 직접적인 답변은 아니지만 강한 관련이 있습니다.

리소스가 다른 파일(예: ResourceDictionary.xaml)에 있는 경우

간단히 추가할 수 있습니다.x:Class다음 중 하나를 선택합니다.

<ResourceDictionary x:Class="Namespace.NewClassName"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
    <ds:MyCollection x:Key="myKey" x:Name="myName" />
</ResourceDictionary>

그런 다음 뒤에 있는 코드로 사용합니다.

var res = new Namespace.NewClassName();
var col = res["myKey"];

다른 클래스(예를 들어 xaml 코드 배후에 없음)에서 리소스에 액세스하려면

Application.Current.Resources["resourceName"];

부터System.Windows네임스페이스.

다음과 같은 리소스 키를 사용할 수 있습니다.

<UserControl.Resources>
    <SolidColorBrush x:Key="{x:Static local:Foo.MyKey}">Blue</SolidColorBrush>
</UserControl.Resources>
<Grid Background="{StaticResource {x:Static local:Foo.MyKey}}" />

public partial class Foo : UserControl
{
    public Foo()
    {
        InitializeComponent();
        var brush = (SolidColorBrush)FindResource(MyKey);
    }

    public static ResourceKey MyKey { get; } = CreateResourceKey();

    private static ComponentResourceKey CreateResourceKey([CallerMemberName] string caller = null)
    {
        return new ComponentResourceKey(typeof(Foo), caller); ;
    }
}

리소스는 C#(데스크탑 WPF W/)에서 입수했습니다.NET Framework 4.8)에서 다음 코드를 사용합니다.

{DefaultNamespace}.Properties.Resources.{ResourceName}

Microsoft 문서의 깔끔한 예를 들면, 다음과 같습니다.

private void myButton_Click(object sender, RoutedEventArgs e)
{
  Button button = (Button)sender;
  button.Background = (Brush)this.FindResource("RainbowBrush");
}

언급URL : https://stackoverflow.com/questions/2117886/accessing-a-resource-via-codebehind-in-wpf