|
Hello,
I'm new to WPF and I'm trying to make at run time a binding to an element that is the value in a dictionary corresponding to a certain key.
I made several tries but the best result I have obtained is to have a binding that is triggered only one time. This is the code.
DictThresholds[thresholdKey] = thresholdValue;
HorizontalLine newThresholdLine = new HorizontalLine();
newThresholdLine.StrokeThickness = 1;
newThresholdLine.Stroke = Brushes.Red;
var binding = new Binding();
binding.Source = DictThresholds[thresholdKey];
newThresholdLine.SetBinding(HorizontalLine.ValueProperty, binding);
plotter.Children.Add(newThresholdLine);
class ThresholdDictionary : INotifyCollectionChanged
{
#region Events
public event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion Events
#region Properties and Attributes
private Dictionary<string, Double> _dictThreshold;
public Double this[string key]
{
get { return _dictThreshold[key]; }
set
{
object oldValue = null;
if (_dictThreshold.ContainsKey(key))
{
oldValue = _dictThreshold[key];
}
_dictThreshold[key] = value;
NotifyPropertyChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, value, oldValue));
}
}
#endregion Properties and Attributes
#region Constructors
public ThresholdDictionary()
{
_dictThreshold = new Dictionary<string, Double>();
}
#endregion Constructors
private void NotifyPropertyChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
{
CollectionChanged(this, e);
}
}
}
}
I would like that the HorizontalLine to be updated each time I update the value corresponding to that key.
Hope you can help me!
Regaards,
Alessandro
|
|
|
|
|
Why not try setting the Binding.Source to the DictThresholds and have a simple converter that does the dictionary lookup using the thresholdKey as the Binding.ConverterParameter ?
var binding = new Binding();
binding.Source = DictThresholds;
binding.Converter = new DictionaryLookupConverter();
binding.ConverterParameter = thresholdKey;
newThresholdLine.SetBinding(HorizontalLine.ValueProperty, binding);
class DictionaryLookupConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
object result;
IDictionary dict = value as IDictionary;
if (dict == null || parameter == null || !dict.TryGetValue(parameter, out result))
{
return DependencyProperty.UnsetValue;
}
return result;
}
}
This works for anything that implements IDictionary . I leave it as an exercise to extend it for IDictionary<TKey, TValue> .
|
|
|
|
|
You're doing it wrong if you are binding from code. Your example can easily be done via XAML. Have an ItemsControl and style it with a DataTemplate.
|
|
|
|
|
Have a look at the ObservableCollection and see how you can implement it in your code.
|
|
|
|
|
Hello,
I have something strange, i have defined two Event Triggers with atched commands in my button:
<i:EventTrigger EventName="MouseLeftButtonDown">
<i:InvokeCommandAction Command="{Binding StartCommand}"/>
</i:EventTrigger>
<i:EventTrigger EventName="MouseLeftButtonUp">
<i:InvokeCommandAction Command="{Binding StopCommand}"/>
</i:EventTrigger>
LEFT MOUSE BUTTON SCENARIO:
When i use those Events:MouseLeftButtonDown ,MouseLeftButtonUp
the StartCommand invoked when i press(with left mouse button) down the button but when i relese the mouse the stop command is not invoked.
RIGHT MOUSE BUTTON SCENARIO:
When i use those Events:MouseRightButtonDown ,MouseRightButtonUp
the StartCommand invoked when i press(with right mouse button) down the button and the StopCommand invoked when i release the button as expected.
What is the problem why the StopCommand is not invoked?
How can i fire off a command when a button is pressed(with left mouse button) and fire off another command when the button released?
Thanks
|
|
|
|
|
Have you tried using PreviewMouseLeftButtonUp ?
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
can you post the code for Mouse down
|
|
|
|
|
What WPF Frameworks are available? What are the pro's/con's? Is there one that stand out as the leader?
Thanks
If it's not broken, fix it until it is
|
|
|
|
|
In fact, WPF itself is a framework (more exactly: It is a graphics framework and part of the even bigger .Net framework [Which is a definition for the .Net framework classes, ASP.Net, SilverLight and WinForms technologies - I am sure there are many others]).
Therefore the .Net framework is the only framework providing "The real WPF", and this leads to the cunclusion that it is the outstanding leader.
On Linux there is the Mono framework as an adaption of the .Net framework, but it is not that wide-spread and I am not sure wether it provides support for WPF.
You know the world is going crazy when the best rapper is a white guy, the best golfer is a black guy, the tallest guy in the NBA is Chinese, the Swiss hold the America's Cup, France is accusing the U.S. of arrogance, Germany doesn't want to go to war, and the three most powerful men in America are named "Bush", "Dick", and "Colon."
|
|
|
|
|
Are you talking about MVVM frameworks? Or are you referring to something like Prism? Application frameworks? This is a very open ended question that is impossible to answer in its current form.
|
|
|
|
|
Are you talking about an MVVM framework? DI / container engine? etc. You're going to get a million different answers. Personally, I wrote my own lifting various parts from various places. I don't know of any (other then my own) that have MVVM stuff + DI + UI rolled into one as those pieces are usually "sold separately". I'd do the same thing if I were you as you almost never need to use the advanced parts of the open source libraries and good luck getting support .
|
|
|
|
|
Prism[^] is a good framework to explore. When setup correctly, Prism and MVVM can complement each other.
|
|
|
|
|
I have a main window that contains buttons to open forms (other windows) for registration. How to open these windows forms inside the main window, the main window active mantento?! I tried with child, but on the menu bar of the windows icon appears for each open form.
|
|
|
|
|
It may be worth learning something of model view presenter(MVP) - this would allow you to display different views within the same main window.
A good introduction can be gained from going through - Sams Teach Yourself WPF in 24 Hours - I found it invaluable in taking me step by step through the process of creating WPF MVP applications.
[edit - corrected typo and grammar]
“That which can be asserted without evidence, can be dismissed without evidence.”
― Christopher Hitchens
modified 16-Oct-13 11:52am.
|
|
|
|
|
If you want to prevent the child icons appearing in the TaskBar, set ShowInTaskBar="False" in the Window section of those forms.
|
|
|
|
|
Being new to WPF I am starting to like the databinding aspect and have a noob question.
If possible I would like to update all elements on the UI via databinding - in some cases I have found this to be very difficult and have resorted to the dispatcher class.
So my question is this - is it possible and desirable to use databinding for everything on the UI or is it considered reasonable to make use of despatcher at times?
Thanks
“That which can be asserted without evidence, can be dismissed without evidence.”
― Christopher Hitchens
|
|
|
|
|
I assume You are using a ViewModel. If so then set the dataContext and then the binding is simple.
Hope this helps.
David
|
|
|
|
|
Thanks
That helped, I had tried it before but had not set up the bound variable as a property.
I changed it to a property, set the datacontext and notify, and it worked!
“That which can be asserted without evidence, can be dismissed without evidence.”
― Christopher Hitchens
|
|
|
|
|
I have found in Silverlight that I almost never use public variables. One of the first things I did was to create a snippet for creating a public property with onpropertychanged for use in VMs
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Yes doubtless silverlight will be next for me - although I understand the step to silverlight is made a lot easier by being familiar with wpf.
“That which can be asserted without evidence, can be dismissed without evidence.”
― Christopher Hitchens
|
|
|
|
|
You need to look into the future of silverlight before making that decision - it does not have one since the plug in model will no longer be supported!
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Once you get a hang of data binging and INotifyPropertyChanged , you should not need to use the dispatcher.
Though a little off-topic, you can also explore attached behaviours[^] in your spare time. These help you get around problems that you could come across while handling events.
|
|
|
|
|
I see that you alread have gotten some very useful comments in this question. I found that If I set the binding in code behind it is easyer to do ceirtain things, like:
Sub SetObjectBinding(ByVal Source As Object, ByVal Path As String, ByVal control As TextBox)
Dim bnd As New Binding
bnd.Path = New PropertyPath(Path)
bnd.Source = Source
bnd.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
bnd.Converter = New DoubleToStringConverter
bnd.ValidationRules.Add(New PositiveDoubleValidator)
control.SetBinding(TextBox.TextProperty, bnd)
End Sub
With the classes:
<ValueConversion(GetType(Double), GetType(String))>
Private Class DoubleToStringConverter
Implements IValueConverter
Public Function Convert(value As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
Return value.ToString
End Function
Public Function ConvertBack(value As Object, targetType As System.Type, parameter As Object, culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
Dim d As Double
Dim str As String = value.ToString
If str.Contains(".") Then str = str.Replace(".", ",")
If Double.TryParse(str, d) Then
If d > 0 Then
Return d
Else
Return DependencyProperty.UnsetValue
End If
End If
Return value.ToString
End Function
End Class
Public Class PositiveDoubleValidator
Inherits ValidationRule
Public Overloads Overrides Function Validate(value As Object, cultureInfo As System.Globalization.CultureInfo) As System.Windows.Controls.ValidationResult
Dim d As Double
Dim str As String = value.ToString
If str.Contains(".") Then str = str.Replace(".", ",")
If Double.TryParse(str, d) Then
If d > 0 Then
Return ValidationResult.ValidResult
Else
Return New ValidationResult(False, "The entered value must be positive")
End If
Else
Return New ValidationResult(False, "The value '" & str & "' could not be converted to a positive number")
End If
End Function
End Class
And in the XAML code:
<Style TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel LastChildFill="True">
<Border BorderBrush="Red" BorderThickness="5">
<AdornedElementPlaceholder />
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
I dont know exactly how this could be done in MVVM but this works for me at least.
|
|
|
|
|
Thanks Kenneth
I will look at this code some evening this week - looks like it will be of great help.
As you say the responses have been very helpful and I am glad that binding is the way to go as using the despatcher feels like a bit of a workaround.
“That which can be asserted without evidence, can be dismissed without evidence.”
― Christopher Hitchens
|
|
|
|
|
Obviously the checks could be made better, but the idea is still the same, and it works quite well for my puropses.
|
|
|
|