简体   繁体   中英

Creating a Rect converter MVVM WPF

I am having trouble creating a converter that will convert an object into a Rect. Irrelevant 'SearchResults' conversion logic is hidden.

The app does not throw any errors, only completely hides the custom element (SearchBox).

Using Rect="0,0,200,40" works fine.

Converter class:

public class SearchResultsToClipRectConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return new Rect(0d, 0d, 200d, 40d);
    }

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

Custom Element Xaml:

<Border 
    CornerRadius="8" x:Name="SearchBorder"
    Background="#2F3F3F"
    Margin="0,10,0,0"
    Width="200"
    Height="{TemplateBinding SearchResults, Converter={StaticResource SearchResultsToStackPanelSizeConverter}}">
    <Border.Clip>
        <RectangleGeometry RadiusX="8" RadiusY="8" Rect="{TemplateBinding SearchResults, Converter={StaticResource SearchResultsToClipRectConverter}}"/>
    </Border.Clip> 
</Border>

The converter is properly referenced in the resource dictionary, there are a few others already (like the one used for Height), no issues there.

I have tried creating a Rect separately from X, Y, Height and Width in xaml, but no luck there, as it throws a conversion error from TemplateBindingExpression to System.Double.

Try to bind to replace the TemplateBinding with a binding to a visual ancestor:

<RectangleGeometry RadiusX="8" RadiusY="8" Rect="{Binding SearchResults, 
    RelativeSource={RelativeSource AncestorType=local:YourControl}, Converter={StaticResource SearchResultsToClipRectConverter}}"/>

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