sourcetip

텍스트 블록 스택을 사용하는 대신 문자열 연결

fileupload 2023. 5. 3. 21:41
반응형

텍스트 블록 스택을 사용하는 대신 문자열 연결

WPF Items Control에서 고객 개체 목록을 표시하려고 합니다.다음을 위해 데이터 템플릿을 만들었습니다.

    <DataTemplate DataType="{x:Type myNameSpace:Customer}">
        <StackPanel Orientation="Horizontal" Margin="10">
            <CheckBox"></CheckBox>
            <TextBlock Text="{Binding Path=Number}"></TextBlock>
            <TextBlock Text=" - "></TextBlock>
            <TextBlock Text="{Binding Path=Name}"></TextBlock>
        </StackPanel>
    </DataTemplate>

그래서 제가 원하는 것은 기본적으로 NUMBER - NAME이 포함된 간단한 목록(체크박스 포함)입니다. Binding 파트에서 번호와 이름을 직접 연결할 수 있는 방법이 없을까요?

StringFormat 속성이 있습니다( 참조).NET 3.5 SP1)을 사용할 수 있습니다.그리고 WPF 바인딩 치트 시트는 여기서 찾을 수 있습니다.도움이 되지 않으면 언제든지 개체에 대한 자체 ValueConverter 또는 사용자 지정 속성을 작성할 수 있습니다.

방금 확인했습니다. 다중 바인딩과 함께 StringFormat을 사용할 수 있습니다.이 경우 코드는 다음과 같습니다.

<TextBlock>
  <TextBlock.Text>
    <MultiBinding StringFormat=" {0} - {1}">
        <Binding Path="Number"/>
        <Binding Path="Name"/>
    </MultiBinding>
  </TextBlock.Text>
</TextBlock>

저는 공간으로 문자열 포맷을 시작해야 했습니다. 그렇지 않으면 Visual Studio가 빌드할 수 없습니다. 하지만 저는 당신이 그것을 피할 방법을 찾을 것이라고 생각합니다. :)

편집
구문 분석기가 처리하지 못하도록 하려면 문자열 형식에 공간이 필요합니다.{0}실질적인 구속력으로서다른 대안:

<!-- use a space before the first format -->
<MultiBinding StringFormat=" {0} - {1}">

<!-- escape the formats -->
<MultiBinding StringFormat="\{0\} - \{1\}">

<!-- use {} before the first format -->
<MultiBinding StringFormat="{}{0} - {1}">

동적 값을 정적 텍스트와 연결하려는 경우 다음을 수행합니다.

<TextBlock Text="{Binding IndividualSSN, StringFormat= '\{0\} (SSN)'}"/>

디스플레이 : 234-334-5566(SSN)

실행 클래스를 사용하여 코드에 사용한 다음 예제를 참조하십시오.

        <TextBlock x:Name="..." Width="..." Height="..."
            <Run Text="Area="/>
            <Run Text="{Binding ...}"/>
            <Run Text="sq.mm"/>
            <LineBreak/>
            <Run Text="Min Diameter="/>
            <Run Text="{Binding...}"/>
            <LineBreak/>
            <Run Text="Max Diameter="/>
            <Run Text="{Binding...}"/>
        </TextBlock >

바인딩 가능한 실행을 사용할 수도 있습니다.특히 텍스트 형식(색상, 글꼴 두께 등)을 추가하려는 경우 유용한 정보입니다.

<TextBlock>
   <something:BindableRun BoundText="{Binding Number}"/>
   <Run Text=" - "/>
   <something:BindableRun BoundText="{Binding Name}"/>
</TextBlock>

여기 오리지널 클래스가 있습니다.
다음은 몇 가지 추가적인 개선 사항입니다.
그리고 그것은 모두 하나의 코드로 되어 있습니다.

public class BindableRun : Run
    {
        public static readonly DependencyProperty BoundTextProperty = DependencyProperty.Register("BoundText", typeof(string), typeof(BindableRun), new PropertyMetadata(new PropertyChangedCallback(BindableRun.onBoundTextChanged)));

        private static void onBoundTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((Run)d).Text = (string)e.NewValue;
        }

        public String BoundText
        {
            get { return (string)GetValue(BoundTextProperty); }
            set { SetValue(BoundTextProperty, value); }
        }

        public BindableRun()
            : base()
        {
            Binding b = new Binding("DataContext");
            b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(FrameworkElement), 1);
            this.SetBinding(DataContextProperty, b);
        }
    }

언급URL : https://stackoverflow.com/questions/541896/concatenate-strings-instead-of-using-a-stack-of-textblocks

반응형