1

I want to bind the TextBox Text to a static property, like https://stackoverflow.com/a/27880765, but can't get it to work. IntelliSense is no help either.


Static Configuration Class:

public static class Configuration
{
    public static string Host { get; set; } = "127.0.0.1";
}

WPF-Window:

<Window x:Class="MyApp.OptionsDialog"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyApp"
        mc:Ignorable="d"
        Title="OptionsDialog" Height="104.563" Width="226.845">
    <Grid Margin="5">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Label Content="Host: " Grid.Column="0" Grid.Row="0"/>
        <TextBox Text="{Binding Source=x:Static local:Configuration.Host}" Grid.Column="1" Grid.Row="0" Margin="1"/>
    </Grid>
</Window>

Things i tried out:

  • {Binding Path={x:Static local:Configuration.Host}, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay} - Getter called, but InvalidCastExcpetion: System.String <=> System.Windows.PropertyPath
  • {Binding Source={x:Static local:Configuration.Host}, Mode=TwoWay} - Getter called, InvalidOperationExcpetion: Bidirectional Binding needs Path or XPath
  • {Binding Source={x:Static local:Configuration.Host}, Mode=TwoWay, Path=.} Getter called and displayed correctly, but no Setter
  • {Binding {x:Static local:Configuration.Host}, Mode=TwoWay} - Getter called but not displayed, Setter not working`

Edit: Why it is NOT a duplicate!

Binding to static property is about static property's in an non static class. I am asking about static propertys in an static class.

Mohammed Li
  • 305
  • 3
  • 12
  • Quote: "Provided the class is not static". Configuration is a static class. – Mohammed Li Oct 10 '17 at 11:24
  • Did you read the second answer, including the comments? Two-way binding requires a path (and the source then needs to be an **object** on which the path will be run). You're trying to bind to a type rather than an object, which works for one-way bindings but clashes with the way two-way bindings inherently work. Why not use a singleton instead? – Flater Oct 10 '17 at 11:28
  • Yes, but I wanted to avoid the Singleton Pattern. The answer is from 2009 and I guessed Microsoft could have added some features to WPF since then. – Mohammed Li Oct 10 '17 at 11:31
  • 1
    [This answer](https://stackoverflow.com/a/31611110/1136211) may be helpful. – Clemens Oct 10 '17 at 11:37
  • 1
    Thanks @Clemens. This was indeed the right answer. – Mohammed Li Oct 10 '17 at 11:43

0 Answers0