wpf 带有静态文本和绑定的标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34621376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:36:37  来源:igfitidea点击:

Label with static text and binding

wpfvb.netxamldata-binding

提问by ARidder101

I am trying to get a label to show specific text while also being bound to a variable in the VB.Net code. I can make a binding but I cant get it to add the static text.

我正在尝试获取一个标签以显示特定文本,同时还绑定到 VB.Net 代码中的变量。我可以进行绑定,但无法添加静态文本。

What I have so far:

到目前为止我所拥有的:

<Label x:Name="TestLabel" Content="{Binding Path=Row, StringFormat='Row #{0}'}" 
                          HorizontalAlignment="Left" 
                          Height="35" 
                          Margin="203,21,0,0" 
                          VerticalAlignment="Top" 
                          Width="83" 
                          FontSize="18">

with

Public Class Row
    Implements INotifyPropertyChanged

    Private _Row As Byte
    Public Property Row() As Byte
        Get
            Return _Row
        End Get
        Set(ByVal value As Byte)
            _Row = value

            OnPropertyChanged(New PropertyChangedEventArgs("Row"))
        End Set
    End Property

    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

    Public Sub OnPropertyChanged(ByVal e As PropertyChangedEventArgs)
        If Not PropertyChangedEvent Is Nothing Then
            RaiseEvent PropertyChanged(Me, e)
        End If
    End Sub
End Class

and

Private Rows As New Row

Public Sub New()
    InitializeComponent()
    TestLabel.DataContext = Rows
    Rows.Row = MyTextBox.Text.HandledStringtoSByte
End Sub

The extension code (since I have a custom extension):

扩展代码(因为我有一个自定义扩展):

''' <summary>
''' Handles conversion of string variable to Tiny Integer
''' </summary>
''' <param name="s"></param>
''' <param name="I">Returned if conversion fails.</param>
''' <returns>Signed 8bit Integer</returns>
''' <remarks></remarks>
<Runtime.CompilerServices.Extension()> _
Public Function HandledStringtoSByte(ByRef S As String, Optional I As SByte = 0) As SByte
    Try
        If S = String.Empty Then
            Return I
        Else
            Return SByte.Parse(S)
        End If
    Catch
        Dim result As String = String.Empty
        Dim ReturnByte As SByte
        Dim Parsed As Byte
        For Each Character In S.ToCharArray
            If Character = "-" Then
                If S.Substring(0, 1).ToString <> "-" Then
                    Exit For
                End If
            End If
            If Character = "." Then
                Exit For
            End If
            If Byte.TryParse(Character, Parsed) Then
                result = result + Parsed.ToString
            End If
        Next
        If result <> String.Empty Then
            If SByte.TryParse(result, ReturnByte) Then
                Return SByte.Parse(ReturnByte)
            Else
                If Short.Parse(result) > Short.Parse(SByte.MaxValue.ToString) Then
                    Return SByte.MaxValue
                ElseIf Short.Parse(result) < Short.Parse(SByte.MinValue.ToString) Then
                    Return SByte.MinValue
                Else
                    Return SByte.Parse(ReturnByte)
                End If
            End If
        Else
            Return I
        End If
    End Try
End Function

Now I thought that using the stringformat in binding would add the static text and place the bound variable into the {0} spot but all is gives me is the bound variable in the label.

现在我认为在绑定中使用 stringformat 会添加静态文本并将绑定变量放入 {0} 点,但所有给我的是标签中的绑定变量。

What am i doing wrong?

我究竟做错了什么?

回答by Fabio

Binding target is Contentproperty which is Objecttype, that is why you cannot use StringFormatwith binding.

绑定目标是类型的Content属性Object,这就是您不能StringFormat与绑定一起使用的原因。

Instead use ContentStringFormatproperty

而是使用ContentStringFormat属性

<Label Content="{Binding Path=Row}"  
       ContentStringFormat="Row #{0}" />

Another approach: create readonly property in the ViewModel which will represent value in wanted format

另一种方法:在 ViewModel 中创建 readonly 属性,该属性将以所需格式表示值

Private _Row As Byte
Public Property Row() As Byte
    Get
        Return _Row
    End Get
    Set(ByVal value As Byte)
        _Row = value
        OnPropertyChanged(New PropertyChangedEventArgs("Row"))
        OnPropertyChanged(New PropertyChangedEventArgs("RowText"))
    End Set
End Property

Public ReadOnly Property RowText As String
    Get
        Return String.Format("Row #{0}", Me.Row)
    End Get
End Property

Then bind this property to the View

然后将此属性绑定到视图

<Label Content="{Binding Path=RowText}"/>

回答by Grx70

The problem is that Binding.StringFormatis "a string that specifies how to format the binding if it displays the bound value as a string". In practice it seems to work only if the target property is of type string- as you pointed out it's working for TextBlock.Text(which is of type string) and not for Label.Content(which is of type object). There are several ways to approach this problem, one of them would be to nest a TextBlockin the Contentproperty:

问题是Binding.StringFormat“一个字符串,如果它将绑定值显示为字符串,则指定如何格式化绑定”。在实践中,它似乎只有在目标属性是 type 时才有效string- 正如您指出的那样,它适用于TextBlock.Text(类型为string)而不适用于Label.Content(类型为object)。有几种方法可以解决这个问题,其中一种方法是TextBlockContent属性中嵌套 a :

<Label>
    <TextBlock Text="{Binding Path=Row, StringFormat='Row #{0}'}" />
</Label>

This doesn't really introduce any additional complexity to the visual tree since strings are by default presented by TextBlocks.

这并没有真正给可视化树带来任何额外的复杂性,因为字符串默认由TextBlocks呈现。

Otherwise you could create your own converter, or you could go with Fabio's solution and utilize Label.ContentStringFormatproperty.

否则,您可以创建自己的转换器,或者您可以使用 Fabio 的解决方案并利用Label.ContentStringFormat属性。

回答by Aybe

Here's a way to bind to multiple properties :

这是一种绑定到多个属性的方法:

  • a MultiBinding
  • an IMultiValueConverter
  • 一种 MultiBinding
  • 一个 IMultiValueConverter

Code:

代码:

Imports System.Globalization
Imports System.Text

Class MainWindow
    Public Shared ReadOnly Text1Property As DependencyProperty = DependencyProperty.Register(
        "Text1", GetType(String), GetType(MainWindow), New PropertyMetadata(Nothing))

    Public Property Text1 As String
        Get
            Return DirectCast(GetValue(Text1Property), String)
        End Get
        Set
            SetValue(Text1Property, Value)
        End Set
    End Property

    Public Shared ReadOnly Text2Property As DependencyProperty = DependencyProperty.Register(
        "Text2", GetType(String), GetType(MainWindow), New PropertyMetadata(Nothing))

    Public Property Text2 As String
        Get
            Return DirectCast(GetValue(Text2Property), String)
        End Get
        Set
            SetValue(Text2Property, Value)
        End Set
    End Property

    Private Sub MainWindow_OnLoaded(sender As Object, e As RoutedEventArgs)
        Me.Text1 = "text1"
        Me.Text2 = "text2"
    End Sub
End Class

Converter:

转换器:

Class MyConverter
    Implements IMultiValueConverter

    Public Function Convert(values As Object(), targetType As Type, parameter As Object, culture As CultureInfo) _
        As Object Implements IMultiValueConverter.Convert

        If values Is Nothing Then
            Return DependencyProperty.UnsetValue
        End If

        Dim sb As New StringBuilder

        If values.Length > 0 Then
            sb.AppendLine(values(0))
        End If

        If values.Length > 1 Then
            sb.AppendLine(values(1))
        End If

        Return sb.ToString()
    End Function

    Public Function ConvertBack(value As Object, targetTypes As Type(), parameter As Object, culture As CultureInfo) _
        As Object() Implements IMultiValueConverter.ConvertBack
        Throw New NotImplementedException
    End Function
End Class

Xaml:

Xml:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="clr-namespace:WpfApplication2"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        x:Name="Window"
        Title="MainWindow"
        Width="525"
        Height="350"
        Loaded="MainWindow_OnLoaded"
        mc:Ignorable="d">
    <Grid>
        <StackPanel>
            <TextBox Text="{Binding ElementName=Window, Path=Text1, UpdateSourceTrigger=PropertyChanged}" />
            <TextBox Text="{Binding ElementName=Window, Path=Text2, UpdateSourceTrigger=PropertyChanged}" />
            <Label>
                <Label.Resources>
                    <local:MyConverter x:Key="MyConverter" />
                </Label.Resources>
                <Label.Content>
                    <MultiBinding Converter="{StaticResource MyConverter}">
                        <Binding ElementName="Window" Path="Text1" />
                        <Binding ElementName="Window" Path="Text2" />
                    </MultiBinding>
                </Label.Content>

            </Label>
        </StackPanel>
    </Grid>
</Window>