programing

StringFormat을 사용한 WPF 바인딩이 ToolTips에서 작동하지 않음

oldcodes 2023. 4. 9. 22:21
반응형

StringFormat을 사용한 WPF 바인딩이 ToolTips에서 작동하지 않음

다음 코드에는 동일한 바인딩 표기법을 사용하여 MyTextBlock이라는 이름의 텍스트 블록의 텍스트를 TextBox의 Text 및 ToolTip 속성에 바인딩하는 단순한 바인딩이 있습니다.

<StackPanel>
    <TextBlock x:Name="MyTextBlock">Foo Bar</TextBlock>
    <TextBox    Text="{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \{0\}'}"
             ToolTip="{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \{0\}'}" />
</StackPanel>

바인딩에서는 도입된StringFormat 속성도 사용됩니다.NET 3.5 SP1은 위의 Text 속성에서는 정상적으로 동작하지만 ToolTip에서는 파손된 것 같습니다.예상되는 결과는 "Foo Bar"이지만 TextBox 위에 마우스를 놓으면 ToolTip에 바인딩 값만 표시되고 문자열 형식 값은 표시되지 않습니다.좋은 생각 있어요?

WPF의 ToolTips에는 텍스트뿐만 아니라 모든 것이 포함될 수 있으므로 텍스트만 원하는 시간에 ContentStringFormat 속성이 제공됩니다.제가 아는 한 확장 구문을 사용해야 합니다.

<TextBox ...>
  <TextBox.ToolTip>
    <ToolTip 
      Content="{Binding ElementName=myTextBlock,Path=Text}"
      ContentStringFormat="{}It is: {0}"
      />
  </TextBox.ToolTip>
</TextBox>

이와 같이 중첩된 속성에서 ElementName 구문을 사용한 바인딩의 유효성에 대해서는 100% 확신할 수 없지만 ContentStringFormat 속성은 원하는 것입니다.

벌레일 수도 있어요.툴팁에 짧은 구문을 사용하는 경우:

<TextBox ToolTip="{Binding WhatEverYouWant StringFormat='It is: \{0\}'}" />

StringFormat은 무시되지만 확장 구문을 사용하는 경우:

<TextBox Text="text">
   <TextBox.ToolTip>
      <TextBlock Text="{Binding WhatEverYouWant StringFormat='It is: \{0\}'}"/>
   </TextBox.ToolTip>
</TextBox>

예상대로 된다.

Matt가 말한 것처럼 ToolTip은 TextBox를 바인딩할 수 있도록 안에 무엇이든 포함할 수 있습니다.ToolTip 내의 텍스트입니다.

<StackPanel>
    <TextBlock x:Name="MyTextBlock">Foo Bar</TextBlock>
    <TextBox Text="{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \{0\}'}">
        <TextBox.ToolTip>
            <TextBlock>
                <TextBlock.Text>
                    <Binding ElementName=MyTextBlock Path="Text" StringFormat="It is: {0}" />
                </TextBlock.Text>
            </TextBlock>
        </TextBox.ToolTip>
    </TextBox>
</StackPanel>

원하는 경우 ToolTip 내부에 그리드를 쌓고 텍스트를 레이아웃할 수도 있습니다.

코드는 다음과 같이 짧을 수 있습니다.

<TextBlock ToolTip="{Binding PrideLands.YearsTillSimbaReturns,
    Converter={StaticResource convStringFormat},
    ConverterParameter='Rejoice! Just {0} years left!'}" Text="Hakuna Matata"/>

String Format과 달리 Converters가 무시되지 않는다는 사실을 사용합니다.

다음 내용을 StringFormatConverter.cs에 게시합니다.

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace TLKiaWOL
{
    [ValueConversion (typeof(object), typeof(string))]
    public class StringFormatConverter : IValueConverter
    {
        public object Convert (object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (ReferenceEquals(value, DependencyProperty.UnsetValue))
                return DependencyProperty.UnsetValue;
            return string.Format(culture, (string)parameter, value);
        }

        public object ConvertBack (object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
}

ResourceDictionary.xaml에 저장합니다.

<conv:StringFormatConverter x:Key="convStringFormat"/>

이 경우 상대 바인딩을 사용할 수 있습니다.

<StackPanel>
    <TextBlock x:Name="MyTextBlock">Foo Bar</TextBlock>
    <TextBox Text="{Binding ElementName=MyTextBlock, Path=Text, StringFormat='It is: \{0\}'}"
             ToolTip="{Binding Text, RelativeSource={RelativeSource Self}}" />
</StackPanel>

다음은 설득력 있는 해결책이지만 효과가 있습니다.

<StackPanel>
  <TextBox Text="{Binding Path=., StringFormat='The answer is: {0}'}">
    <TextBox.DataContext>
      <sys:Int32>42</sys:Int32>
    </TextBox.DataContext>
    <TextBox.ToolTip>
      <ToolTip Content="{Binding}" ContentStringFormat="{}The answer is: {0}" />
    </TextBox.ToolTip>
  </TextBox>
</StackPanel>

나는 내가 처음 질문했던 것과 같은 훨씬 간단한 구문을 선호한다.

언급URL : https://stackoverflow.com/questions/197095/wpf-binding-with-stringformat-doesnt-work-on-tooltips

반응형