wpf 代码隐藏中的绑定(转换器)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33481720/
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:30:52  来源:igfitidea点击:

Binding(Converter) in Code Behind

c#wpfxamldatatemplatestaticresource

提问by ntohl

<local:LabelTemp x:Key="labelTemplate"/>
        <DataTemplate x:Key="labelTemp">
            <TextBlock Text="{Binding Converter={StaticResource labelTemplate},Path=Item.Items}"/>
        </DataTemplate>

Can anyone help me how to write the above Xaml code into Code Behind C#. Im using this code into Pie Chart LabelTemplate.

任何人都可以帮助我如何将上述 Xaml 代码写入 C# 背后的代码。我将此代码用于饼图标签模板。

回答by ntohl

I don't what is the binding source, or how the Pie Chart LabelTemplate (converter) look like. The best I can come up with that much information is the following:

我不知道绑定源是什么,也不知道饼图 LabelTemplate(转换器)的样子。我能想出的最好的信息如下:

public class LabelTemplate : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        //...
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        //...
    }
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        LabelTemplate labelTemplateConverter = new LabelTemplate();
        Binding binding = new Binding("Item.Items");
        binding.Converter = labelTemplateConverter;
        txtBlock.SetBinding(TextBlock.TextProperty, binding);
    }
}

and Your textblock have the Name txtBlock

并且您的文本块的名称为 txtBlock

I hope this helps.

我希望这有帮助。