Click here to Skip to main content
15,890,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am pretty new to WPF. I have a value from app.config. I want to binding a label to this value.
C#
<StackPanel Margin="10" VerticalAlignment="Top">
       <DockPanel VerticalAlignment="Center" Margin="10">
           <Label DockPanel.Dock="Left" FontWeight="Bold" Target="{Binding}">Connect to Server:</Label>
       </DockPanel>

Say
C#
var value = System.Configuration.ConfigurationManager.AppSettings["Key"]
               .ToString(); //1.1.1.1

What I want is the label content become:
Connect to Server: 1.1.1.1
Posted

1 solution

I call it "CBS" (Compulsory Binding Syndrome). The solution is:
C#
labelKey.Content = value;
// Do I even have to explain why?

Of course, you need to add the attribute Name="labelKey" in XAML line with label declaration: <Label Name="labelKey" ... />.

References:
http://msdn.microsoft.com/en-us/library/system.windows.controls.label%28v=vs.110%29.aspx[^],
http://en.wikipedia.org/wiki/KISS_principle[^].

The real purposes of binding are different. You may want to read on the topic.
We had an anecdote circulating, about one of the countries with notoriously spicy, peppery cuisine:


One traveler had trouble with this peppery cuisine, barely able to tolerate so much pepper. One day, he was sitting in a restaurant, thinking "What can I order to avoid getting so much pepper?". He got an idea an called a waiter:

"— Please, I want boiled eggs. Yes, just boiled, unshelled; serve the whole eggs, in the shells."

The kitchen did not produce anything for an hour or two; people started to worry.

"— What takes so long?"

"— Out chef is brainstorming with all the personnel: how to inject pepper in those eggs."
If you want boiled eggs, just boil them.

—SA
 
Share this answer
 
v5
Comments
[no name] 17-Oct-14 11:39am    
Two questions:
1) Label doesn't have Text property. 'System.Windows.Controls.Label' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type 'System.Windows.Controls.Label' could be found (are you missing a using directive or an assembly reference?)

2). I created a class "MainViewModel", I want to put it there.
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
Sergey Alexandrovich Kryukov 17-Oct-14 12:00pm    
Ah! Sorry for the confusion! If should be "Content", of course. I fixed the answer.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900