Связать с методом в WPF?

Когда вы используете путь, начинающийся с ./, это означает, что путь должен начинаться с текущего каталога. Если ваш файл main.css находится в папке приложения, он правильно импортирует файл roboto-font.css.

Однако файл roboto-font.css пытается импортировать файл шрифта из пути ./assets/Roboto/Roboto-Thin.ttf, а сам roboto-font.css уже находится внутри assets/Roboto. Вы должны удалить assets/Roboto из этого свойства url(), поскольку все файлы шрифтов уже находятся в том же каталоге, что и эта таблица стилей. Попробуйте использовать url(./Roboto-Thin.ttf).

Также попробуйте использовать соответствующие форматы веб-шрифтов или просто импортируйте их из Google, как предложено @Radu.

87
задан Paolo Moretti 16 July 2012 в 13:07
поделиться

6 ответов

Не уверенный, как хорошо это будет работать в Вашем сценарии, но можно использовать , свойство MethodName на ObjectDataProvider, чтобы иметь его называет определенный метод (с определенными параметрами если Вы свойство MethodParameters) для получения его данных.

Вот отрывок, взятый непосредственно от страницы MSDN:

<Window.Resources>
    <ObjectDataProvider ObjectType="{x:Type local:TemperatureScale}"
        MethodName="ConvertTemp" x:Key="convertTemp">
        <ObjectDataProvider.MethodParameters>
            <system:Double>0</system:Double>
             <local:TempType>Celsius</local:TempType>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>

, Таким образом, это - ObjectDataProvider, который это называет методом "ConvertTemp" на экземпляре класса "TemperatureScale", передавая два параметра (0 и TempType.Celsius).

24
ответ дан Matt Hamilton 24 November 2019 в 07:51
поделиться

Если Вы не можете добавить свойство для вызова метода (или создать класс обертки, который добавляет, что свойство), единственный способ, о котором я знаю, использует ValueConverter.

4
ответ дан Nir 24 November 2019 в 07:51
поделиться

ObjectDataProvider также имеет свойство ObjectInstance, которое может использоваться вместо ObjectType

3
ответ дан Graham Ambrose 24 November 2019 в 07:51
поделиться

Необходимо ли связать с методом?

можно ли связать со свойством, кто метод считывания, метод?

public ObservableCollection<ChildObject> Children
{
   get
   {
      return GetChildren();
   }
}
9
ответ дан Michael Prewecki 24 November 2019 в 07:51
поделиться

Another approach that might work for you is to create a custom IValueConverter that takes a method name as a parameter, so that it would be used like this:

ItemsSource="{Binding 
    Converter={StaticResource MethodToValueConverter},
    ConverterParameter='GetChildren'}"

This converter would find and invoke the method using reflection. This requires the method to not have any arguments.

Here's an example of such a converter's source:

public sealed class MethodToValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var methodName = parameter as string;
        if (value==null || methodName==null)
            return value;
        var methodInfo = value.GetType().GetMethod(methodName, new Type[0]);
        if (methodInfo==null)
            return value;
        return methodInfo.Invoke(value, new object[0]);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException("MethodToValueConverter can only be used for one way conversion.");
    }
}

And a corresponding unit test:

[Test]
public void Convert()
{
    var converter = new MethodToValueConverter();
    Assert.AreEqual("1234", converter.Convert(1234, typeof(string), "ToString", null));
    Assert.AreEqual("ABCD", converter.Convert(" ABCD ", typeof(string), "Trim", null));

    Assert.IsNull(converter.Convert(null, typeof(string), "ToString", null));

    Assert.AreEqual("Pineapple", converter.Convert("Pineapple", typeof(string), "InvalidMethodName", null));
}

Note that this converter does not enforce the targetType parameter.

68
ответ дан 24 November 2019 в 07:51
поделиться

You can use System.ComponentModel to define properties for a type dynamically (they're not part of the compiled metadata). I used this approach in WPF to enable binding to a type that stored its values in fields, as binding to fields is not possible.

The ICustomTypeDescriptor and TypeDescriptionProvider types might allow you to achieve what you want. According to this article:

TypeDescriptionProvider allows you to write a separate class that implements ICustomTypeDescriptor and then to register this class as the provider of descriptions for other types.

I haven't tried this approach myself, but I hope it's helpful in your case.

3
ответ дан 24 November 2019 в 07:51
поделиться
Другие вопросы по тегам:

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