带转换器的C#WPF绑定路径数据

时间:2017-01-16 14:11:24

标签: c# wpf data-binding

我在将字符串转换为图标时遇到问题。图标Geometry位于ResourceDictionary中。未调用ValueConverter(我尝试在转换器的转换方法中进行调试)。这是我的代码:

XAML:

<Window.Resources>
    <local:StatusToPathDataConverter x:Key="PathConverter"/>
</Window.Resources>
<Grid>
    <Path Width="20"
        Height="20"
        Stretch="Uniform"
        Fill="Black" 
        Data="{Binding Path=Status,
             UpdateSourceTrigger=PropertyChanged, 
             Converter={StaticResource PathConverter}}"/>
</Grid>

CS:

public partial class MainWindow :Window {
    public MainWindow() {
        InitializeComponent();
    }

    public string Status
    {
        get { return (string)GetValue(StatusProperty); }
        set { SetValue(StatusProperty, value); }
    }

    public static readonly DependencyProperty StatusProperty =
         DependencyProperty.Register("Status", typeof(string), typeof(MainWindow));


}
public class StatusToPathDataConverter :IValueConverter {
    private static ResourceDictionary iconDictionary;
    public ResourceDictionary IconDictionary
    {
        get
        {
            if(iconDictionary == null) {
                iconDictionary = new ResourceDictionary();
                iconDictionary.Source = new Uri("/WPFBindingTest;component/Resources/IconDictionary.xaml", UriKind.RelativeOrAbsolute);
            }
            return iconDictionary;
        }
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        var status = (string)value;
        if(statinStatus == null)
            return null;
        switch(status.ToLower()) {
            case "test":
                return IconDictionary["TestIcon"];
                // ...
        }
        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
        throw new NotImplementedException();
    }
}

2 个答案:

答案 0 :(得分:2)

你没有约束力。您需要告诉Binding转到Window才能找到Status媒体资源。建议的方法是使用RelativeSource,如下所示:

<Path 
    Width="20"
    Height="20"
    Stretch="Uniform"
    Fill="Black" 
    Data="{Binding Path=Status,
         RelativeSource={RelativeSource AncestorType=Window},
         Converter={StaticResource PathConverter}}"
         />

正如@Clemens指出的那样,UpdateSourceTrigger=PropertyChanged对此绑定没有任何意义,不应该存在。该属性告诉Binding何时应该更新绑定的source属性。在这种情况下,source属性为Window.Status

但是,Path.Data属性不会更新它所绑定的属性。 Path显示Geometry;它没有编辑GeometryUpdateSourceTrigger存在用于更新viewmodel属性的控件属性,如TextBox.Text。这是UpdateSourceTrigger=PropertyChanged最常见的用途:默认TextBox.TextTextBox失去焦点时更新源属性,但有时您希望在每次击键时更新源属性。

答案 1 :(得分:0)

将窗口的DataContext设置为自身以使绑定正常工作,并将转换器的Convert方法调用:

public MainWindow() {
    InitializeComponent();
    DataContext = this;
}

如果对source属性的绑定失败,则永远不会调用转换器。