Можно ли переопределить просто часть шаблона управления в Silverlight

Пожалуйста, измените в соответствии с вашими потребностями

func upload(image: Data, to url: Alamofire.URLRequestConvertible, params: [String: Any]) {
    AF.upload(multipartFormData: { multiPart in
        for (key, value) in params {
            if let temp = value as? String {
                multiPart.append(temp.data(using: .utf8)!, withName: key)
            }
            if let temp = value as? Int {
                multiPart.append("\(temp)".data(using: .utf8)!, withName: key)
            }
            if let temp = value as? NSArray {
                temp.forEach({ element in
                    let keyObj = key + "[]"
                    if let string = element as? String {
                        multiPart.append(string.data(using: .utf8)!, withName: keyObj)
                    } else
                        if let num = element as? Int {
                            let value = "\(num)"
                            multiPart.append(value.data(using: .utf8)!, withName: keyObj)
                    }
                })
            }
        }
        multiPart.append(image, withName: "file", fileName: "file.png", mimeType: "image/png")
    }, with: url)
        .uploadProgress(queue: .main, closure: { progress in
            //Current upload progress of file 
            print("Upload Progress: \(progress.fractionCompleted)")
        })
        .responseJSON(completionHandler: { data in
            //Do what ever you want to do with response
        })
}
6
задан mattmanser 23 April 2009 в 15:25
поделиться

4 ответа

Я нашел способ сделать это, унаследовав элемент управления и переопределив OnApplyTemplate. Это не идеально, но я думаю, что это лучше, чем копировать весь шаблон управления. Вот пример создания текстового поля без полей, по сути, отключающего указатель мыши над визуальным состоянием, всегда очищая раскадровку:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace SilverlightTestApplication
{
    public class BorderlessTextBox  : TextBox
    {
        public BorderlessTextBox()
        {
            BorderThickness = new System.Windows.Thickness(0);
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            //Get the mouse over animation in the control template
            var MouseOverVisualState = GetTemplateChild("MouseOver") as VisualState;

            if (MouseOverVisualState == null)
                return;

            //get rid of the storyboard it uses, so the mouse over does nothing
            MouseOverVisualState.Storyboard = null;
        }
    }
}
5
ответ дан 17 December 2019 в 00:14
поделиться

Получите шаблон по умолчанию для каждого элемента управления с помощью считывателя XAML, затем скопируйте / вставьте и измените то, что вы хотите ... не очень чисто, но я думаю, что это единственный способ (я поиск, как получить этот шаблон по умолчанию)

0
ответ дан 17 December 2019 в 00:14
поделиться

Its been awhile since I used XAML, but no, I don't believe you can just modify a piece of the template.

However if you have the IDE you can create a copy of the currently applied template and just modify the piece you want and leave the rest as is. See the How to Edit section of this link.

2
ответ дан 17 December 2019 в 00:14
поделиться

В WPF, если вы не уверены, что в Silverlight есть фрагмент кода для получения шаблона Aero, вы можете попробовать скопировать / вставить и изменить то, что вы хотите:

        public Window1()
        {
            InitializeComponent();
            using(FileStream fs = new FileStream("C:/TextBoxTemplate.xaml", FileMode.Create))
            {
                var res = LoadThemeDictionary(typeof(TextBox), "Aero", "NormalColor");
                var buttonRes = res[typeof(TextBox)];
                XamlWriter.Save(buttonRes, fs);
            }
        }

        public static ResourceDictionary LoadThemeDictionary(Type t,
        string themeName, string colorScheme)
        {
            Assembly controlAssembly = t.Assembly;
            AssemblyName themeAssemblyName = controlAssembly.GetName();

            object[] attrs = controlAssembly.GetCustomAttributes(
                    typeof(ThemeInfoAttribute), false);
            if(attrs.Length > 0)
            {
                ThemeInfoAttribute ti = (ThemeInfoAttribute)attrs[0];

                if(ti.ThemeDictionaryLocation ==
                                                         ResourceDictionaryLocation.None)
                {
                    // There are no theme-specific resources.
                    return null;
                }

                if(ti.ThemeDictionaryLocation ==
                                ResourceDictionaryLocation.ExternalAssembly)
                {
                    themeAssemblyName.Name += "." + themeName;
                }
            }

            string relativePackUriForResources = "/" +
                    themeAssemblyName.FullName +
                    ";component/themes/" +
                    themeName + "." +
                    colorScheme + ".xaml";

            Uri resourceLocater = new System.Uri(
                    relativePackUriForResources, System.UriKind.Relative);

            return Application.LoadComponent(resourceLocater)
                                 as ResourceDictionary;
        }

Я никогда не использовал Silverlight, но я не думаю, что есть много вещей, чтобы адаптировать этот шаблон к Silverlight.

Источник: Шаблон по умолчанию в WPF

0
ответ дан 17 December 2019 в 00:14
поделиться
Другие вопросы по тегам:

Похожие вопросы: