DataContext 문자열 속성을 정적 소송 키에 바인딩합니다
-
22-08-2019 - |
문제
리소스키와 캡션이있는 목록 값이 있습니다.이 값은 둘 다 문자열입니다. 리소스는 리소스 사전에 정의 된 실제 리소스의 이름입니다. 이러한 리소스키 아이콘은 각각 캔버스입니다.
<Data ResourceKey="IconCalendar" Caption="Calendar"/>
<Data ResourceKey="IconEmail" Caption="Email"/>
그런 다음 버튼이있는 DataTemplate과 버튼 아래에 텍스트 캡션이있는 목록보기가 있습니다. 내가하고 싶은 것은 자원 정적 자원을 버튼의 컨텐츠로 표시하는 것입니다.
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button Content="{Binding ResourceKey}" Template="{StaticResource RoundButtonControlTemplate}"/>
<TextBlock Grid.Row="1" Margin="0,10,0,0" Text="{Binding Caption}" HorizontalAlignment="Center" FontSize="20" FontWeight="Bold" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
나는 정적 소스를 바인딩하는 모든 순열을 시도했다고 생각합니다.
나는 대안에 열려 있습니다. 이미지를 가지고 소스 속성을 설정하는 것이 더 쉬울 수 있습니다.
감사
해결책
조금만 생각한 후에 ValueConvertor
그렇게 :
class StaticResourceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var resourceKey = (string)value;
return Application.Current.Resources[resourceKey];
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new Exception("The method or operation is not implemented.");
}
}
버튼의 바인딩이됩니다
<Button Content="{Binding ResourceKey, Converter={StaticResource resourceConverter}}" />
다른 팁
여기에 @dvkwong의 답변이 개선되었습니다 (@anatoliy nikolaev의 편집과 함께) :
class StaticResourceConverter : MarkupExtension, IValueConverter
{
private Control _target;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var resourceKey = (string)value;
return _target?.FindResource(resourceKey) ?? Application.Current.FindResource(resourceKey);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
var rootObjectProvider = serviceProvider.GetService(typeof(IRootObjectProvider)) as IRootObjectProvider;
if (rootObjectProvider == null)
return this;
_target = rootObjectProvider.RootObject as Control;
return this;
}
}
용법:
<Button Content="{Binding ResourceKey, Converter={design:StaticResourceConverter}}" />
여기서 주요 변화는 다음과 같습니다.
변환기는 이제 a
System.Windows.Markup.MarkupExtension
따라서 자원으로 선언되지 않고 직접 사용할 수 있습니다.컨버터는 컨텍스트 인식이므로 앱의 리소스뿐만 아니라 로컬 리소스 (현재 창, UserControl 또는 페이지 등)를 조회합니다.
제휴하지 않습니다 StackOverflow