简体   繁体   中英

Generic WPF Binding in C#?

I would like to write a generic function that creates bindings given a pair of FrameworkElements (source/target), a DependencyProperty, and a BindingMode (purely for demonstration/experimentation purposes, trying to create 5 buttons that demonstrate each BindingMode between a slider and a Label.FontSize).

Here is the function I've got to start with:

private void create_Binding(FrameworkElement source, FrameworkElement target, 
                            DependencyProperty property, BindingMode mode) {
            Binding binding = new Binding();
            binding.Source = source;
            binding.Path = new PropertyPath("Value");
            binding.Mode = mode;
            target.SetBinding((target.GetType()).property, binding);
}

Issue: I get CS1061 "'Type' does not contain a definition for 'property'..." on the SetBinding() call. I've tried casting target to a few different types on the last line, but I can't figure out how to make it work.

It could look like this:

private void CreateBinding(
    object sourceObject, string sourcePropertyName,
    DependencyObject targetObject, DependencyProperty targetProperty,
    BindingMode bindingMode)
{
    var binding = new Binding
    {
        Source = sourceObject,
        Path = new PropertyPath(sourcePropertyName),
        Mode = bindingMode
    };

    BindingOperations.SetBinding(targetObject, targetProperty, binding);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM