關於動態字串的繫結

孤沉發表於2024-03-08

WPF的繫結實在是太強大了
1、正常情況下,我們的繫結是這樣的,列印HelloWorld

 <TextBlock Width="200" Height="30" FontSize="20" Text="{Binding Content}"/>
private string _content;

public string Content
{
	get 
    {
        return _content;
    }
	set { SetProperty<string>(ref _content, value); }
}

public PreviewStringViewModel()
{
    Content = "HelloWorld";
}

而在必要的時候,我們需要對繫結的字串進行處理,我這裡只做簡單處理,看似動態,實際靜態,動態需要你們重新加一個動態規劃,道理是一樣的,我只是舉個例子
2、現在開始列印HelloWorld!

<TextBlock Width="200" Height="30" FontSize="20" Text="{Binding Content}"/>
private string _content;

public string Content
{
	get 
    {
        return _content+"!";
    }
	set { SetProperty<string>(ref _content, value); }
}

public PreviewStringViewModel()
{
    Content = "HelloWorld";
}

3、使用轉換器

public class StringToConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string data)
        {
            return data + "!";
        }
        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
 <UserControl.Resources >
     <cvt:StringToConverter x:Key="stringTo"/>
 </UserControl.Resources>
 <Grid>
     <TextBlock
         Width="200"
         Height="30"
         FontSize="20"
         Text="{Binding Content, Converter={StaticResource stringTo}}" />
 </Grid>
 private string _content;

public string Content
{
    get
    {
        return _content ;
    }
    set { SetProperty<string>(ref _content, value); }
}

public StringConverViewModel()
{
    Content = "HelloWorld";
}

4、使用Stringformat

 <TextBlock
     Width="200"
     Height="30"
     FontSize="20"
     Text="{Binding Content, StringFormat={}{0}!}" />
	  private string _content;

public string Content
{
    get
    {
        return _content ;
    }
    set { SetProperty<string>(ref _content, value); }
}

public StringConverViewModel()
{
    Content = "HelloWorld";
}

5、使用MultiBinding

相關文章