从WPF/XAML中的字符串末尾清除空格

Tom*_*Tom 5 c# data-binding wpf xaml mvvm

我有一个MVVM应用程序,它使用一个填充了图像的列表框.图像字符串总是来自我无法修改的对象,因为它是使用edmx模型生成的.

为了剪切一个故事,我需要在下面的xaml中添加一种方法,通过SQL从字符串中修剪放在图像路径末尾的空白.

<ListBox ItemsSource="{Binding AllImages}" x:Name="listBox1" Width="300" Margin="10,10,0,10">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Grid.Column="0" Source="{Binding imagePath}" Height="100" Width="100" />
                <TextBlock Grid.Column="1" Text="{Binding imageId}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

这可能吗?

H.B*_*.B. 8

在绑定中使用值转换器为您进行修剪.


MyK*_*SKI 5

如果您不想使用转换器,您可以直接进入您的财产

INotifyChangedProperty解决方案

private string _ImageID;
public string ImageID
{
    get
    {
        return _ImageID;
    }

    set
    {
       value = (value == null ? value : value.Trim());
       NotifyPropertyChanged("ImageID");
    }
}
Run Code Online (Sandbox Code Playgroud)

DependencyProperty解决方案

public static readonly DependencyProperty ImageIDProperty =
    DependencyProperty.Register("ImageID", typeof(string), typeof(MainWindowViewModel), new PropertyMetadata(string.Empty));

    public string ImageID
    {
        get { return (string)GetValue(ImageIDProperty); }
        set { SetValue(ImageIDProperty, value == null ? value : value.Trim()); }
    }
Run Code Online (Sandbox Code Playgroud)

  • 通常,“ImageID”包装器中不应包含任何代码,它不会为 XAML 或绑定中的值调用。 (2认同)