Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding from System.Windows.SystemParameters.PrimaryScreenWidth with a Converter

I'm trying to bind System.Windows.SystemParameters.PrimaryScreenWidth to a ColumnDefinition's (From within a 'Grid') Width property, and using a converter to convert the 'PrimaryScreenWidth' into a 'GridLength'. But it never gets inside the 'convert' code.

Here's my XAML:

<Window.Resources>
   <local:ScreenWidthToLeftBarWidth x:Key="leftBarConverter" />
</Window.Resources>
<ColumnDefinition Width="{Binding ElementName=System.Windows.SystemParameters, Path=PrimaryScreenWidth, Converter={StaticResource leftBarConverter}}"/>

Here's my CodeBehind for the converter (leaving out the 'ConvertBack' method:

public class ScreenWidthToLeftBarWidth : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            double aValue = (double)value;
            GridLength newWidth = new GridLength(aValue);
            return (newWidth);
        }
    }

Now, I've been able to bind successfully in a slightly different scenario of using a 'Button' objects Width and running it through a converter, So I'm thinking the problem is with how I'm trying to bind from the "ElementName=System.Windows.SystemParameters". Any help appreciated, thanks.

like image 947
Evan Sevy Avatar asked Feb 21 '23 23:02

Evan Sevy


1 Answers

ElementName is for other elements in XAML; for this you will need something like x:Static, e.g.

Width="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth},
                Converter=...}"
like image 117
H.B. Avatar answered Apr 27 '23 19:04

H.B.