Can I dynamically make part of the TextBlock.Text to different colour? - c#

I have TextBlock in my main form. I set the Text property to different strings during the application run.
I would like to be able to colour parts of particular strings.
Pseudo code:
if(a < 0) txbStatus.Text = string.Format("{0} <RED>{1}</RED>", a, b);
else txbStatus.Text = string.Format("{0} <BLUE>{1}</RED>", a, b);

You can split your string the way u want and then using a foreach() loop for that split string try
TextBlockName.Inlines.Add(new Run("colored text") {Foreground = Brushes.Blue});

The content of a TextBox doesn't have to be just a string, but a collection of Inlines:
txbStatus.Inlines.Clear();
txbStatus.Inlines.Add(new Run("normal color, "));
txbStatus.Inlines.Add(new Run("colored text") { Foreground = Brushes.Red });

I have created a custom TextBlock which will help you to highlight some part of text within the TextBlock's "Text" value.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
namespace UI.WPF.UserControls
{
class CustomTextBlock:TextBlock
{
string _originalText;
public string HighlighText
{
get { return (string)GetValue(HighlighTextProperty); }
set
{
SetValue(HighlighTextProperty, value);
RenderHighlightedText();
}
}
// Using a DependencyProperty as the backing store for HighlighText. This enables animation, styling, binding, etc...
public static readonly DependencyProperty HighlighTextProperty =
DependencyProperty.Register("HighlighText", typeof(string), typeof(CustomTextBlock),
new FrameworkPropertyMetadata(new PropertyChangedCallback(HighlighTextProperty_Changed))
);
private static void HighlighTextProperty_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CustomTextBlock textBlock = (CustomTextBlock)d;
textBlock.RenderHighlightedText();
}
public CustomTextBlock()
: base()
{
}
static CustomTextBlock()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(CustomTextBlock),
new FrameworkPropertyMetadata(typeof(CustomTextBlock)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
}
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
_originalText = Text;
RenderHighlightedText();
}
private Run GetFormatedText(string text, bool isBold)
{
Run noramlRun = new Run(text);
if (isBold)
{
noramlRun.FontWeight = FontWeights.Bold;
}
else
{
noramlRun.FontWeight = FontWeights.Normal;
}
return noramlRun;
}
public void RenderHighlightedText()
{
var boldText = HighlighText;
if (!string.IsNullOrEmpty(HighlighText) &&
_originalText.ToLower().Contains(boldText.ToLower()))
{
this.Inlines.Clear();
int point = _originalText.ToLower().IndexOf(boldText.ToLower());
string strHighlighted = _originalText.Substring(point, HighlighText.Length);
Run runHighlight = GetFormatedText(strHighlighted, true);
if (point == 0)
{
this.Inlines.Add(runHighlight);
int remainingLength = _originalText.Length - (point + HighlighText.Length);
string remaingText = _originalText.Substring((point + HighlighText.Length), remainingLength);
this.Inlines.Add(GetFormatedText(remaingText, false));
}
else
{
string firstPart = _originalText.Substring(0, point);
this.Inlines.Add(GetFormatedText(firstPart, false));
this.Inlines.Add(runHighlight);
int remainingLength = _originalText.Length - (point + HighlighText.Length);
string remaingText = _originalText.Substring((point + HighlighText.Length), remainingLength);
this.Inlines.Add(GetFormatedText(remaingText, false));
}
}
else
{
this.Inlines.Clear();
this.Inlines.Add(GetFormatedText(_originalText, false));
}
}
}
}
The Way to use it.
<usercontrol:CustomTextBlock Text="{Binding Title}"
HighlighText="{Binding DataContext.SearchText, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Page}}}"
/>
For more information
https://sites.google.com/site/greateindiaclub/mobil-apps/windows8/highlightpartoftextinwpftextblockcontrol

Related

Custom Picker Xamarin Android

I have a picker.Please,tell me how to change color of title, the color of items and remove these lines
I have my custompicker and I could change colors of buttons CANCEL,OK
I tried to remove lines
https://forums.xamarin.com/discussion/78693/how-can-i-remove-the-picker-borders-in-forms-for-android
but it does not work
How to change color of SELECT A CAR and AUDI I do not know
You could implement it by using Custom Renderer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using App12.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Color = Android.Graphics.Color;
using Orientation = Android.Widget.Orientation;
[assembly: ExportRenderer(typeof(Picker), typeof(MyPickerRenderer))]
namespace App12.Droid
{
public class MyPickerRenderer:PickerRenderer
{
IElementController ElementController => Element;
public MyPickerRenderer(Context context) : base(context)
{
}
private AlertDialog _dialog;
protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
{
base.OnElementChanged(e);
Control.Click += Control_Click;
Control.SetHintTextColor(Android.Graphics.Color.Red);
Control.SetSingleLine(true);
Control.SetTypeface(null, TypefaceStyle.Bold);
Control.Gravity = GravityFlags.Center;
var gd = new GradientDrawable();
gd.SetStroke(0, Android.Graphics.Color.Transparent);
Control.SetBackground(gd);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Control.Click -= Control_Click;
//var picker = (Picker)Element;
//picker.PropertyChanged -= Control_Click;
}
base.Dispose(disposing);
}
private void Control_Click(object sender, EventArgs e)
{
Picker model = Element;
picker.SelectionDividerHeight = 0;
var picker = new TextColorNumberPicker(Context);
if (model.Items != null && model.Items.Any())
{
// set style here
picker.MaxValue = model.Items.Count - 1;
picker.MinValue = 0;
picker.SetDisplayedValues(model.Items.ToArray());
picker.WrapSelectorWheel = false;
picker.Value = model.SelectedIndex;
}
var layout = new LinearLayout(Context) { Orientation = Orientation.Vertical };
layout.AddView(picker);
var titleView = new TextView(Context);
titleView.Text = "Select a car";
titleView.TextSize = 20;
titleView.SetTextColor(Color.Red);
titleView.SetBackgroundColor(Color.White);
ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, true);
var builder = new AlertDialog.Builder(Context);
builder.SetView(layout);
builder.SetTitle(model.Title ?? "");
builder.SetCustomTitle(titleView);
builder.SetNegativeButton("Cancel ", (s, a) =>
{
ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
// It is possible for the Content of the Page to be changed when Focus is changed.
// In this case, we'll lose our Control.
Control?.ClearFocus();
_dialog = null;
});
builder.SetPositiveButton("Ok ", (s, a) =>
{
ElementController.SetValueFromRenderer(Picker.SelectedIndexProperty, picker.Value);
// It is possible for the Content of the Page to be changed on SelectedIndexChanged.
// In this case, the Element & Control will no longer exist.
if (Element != null)
{
if (model.Items.Count > 0 && Element.SelectedIndex >= 0)
Control.Text = model.Items[Element.SelectedIndex];
ElementController.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
// It is also possible for the Content of the Page to be changed when Focus is changed.
// In this case, we'll lose our Control.
Control?.ClearFocus();
}
_dialog = null;
});
_dialog = builder.Create();
_dialog.DismissEvent += (ssender, args) =>
{
ElementController?.SetValueFromRenderer(VisualElement.IsFocusedProperty, false);
};
_dialog.Show();
Android.Widget.Button btnOk = _dialog.GetButton((int)Android.Content.DialogButtonType.Positive);
btnOk.SetTextColor(Android.Graphics.Color.Blue);
Android.Widget.Button btnCancel = _dialog.GetButton((int)Android.Content.DialogButtonType.Positive);
btnCancel.SetTextColor(Android.Graphics.Color.Gray);
}
}
public class TextColorNumberPicker : NumberPicker
{
public TextColorNumberPicker(Context context) : base(context)
{
}
public override void AddView(Android.Views.View child, int index, ViewGroup.LayoutParams #params)
{
base.AddView(child, index, #params);
UpdateView(child);
}
public void UpdateView(Android.Views.View view)
{
if (view is EditText)
{
((EditText)view).SetTextColor(Color.Red); // set item text color
}
}
}
}
Note : Make sure the Target Framework of the project is the latest stable version (Android Q) .
Override Xamarin.Forms.Platform.Android.AppCompat.PickerRenderer instead of Xamarin.Forms.Platform.Android.PickerRenderer
public class CustomPickerRenderer
: Xamarin.Forms.Platform.Android.AppCompat.PickerRenderer
{
...
}
Reference: https://www.damirscorner.com/blog/posts/20201204-CustomPickerRendererOnAndroid.html

TextBox.Text value not updating when being set

Problem:
DecimalTextBox has value set to "" after the line of code txtSickTime.Text = newTest.PutThisDecimalInTheBox.ToString();
The variable txtSickTime.Text = newTest.PutThisDecimalInTheBox.ToString(); has it's value shown in visual studio as 320.5, So shouldn't this when converted to a string be able to be put in the DecimalTextBox without error?
Frontend
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:MegA="clr-namespace:MegA;assembly=MegA" x:Class="WpfApplication14.MainWindow"
Title="MainWindow" Height="350" Width="525"
Loaded="Window_Loaded">
<Grid>
<MegA:DecimalTextBox DollarPrecision="12" Height="22.864" Name="txtSickTime" Width="60.00" MaxLength="4" TabIndex="230" DecimalPrecision="2"/>
</Grid>
</Window>
Backend
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
namespace WpfApplication14
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Test newTest = new Test();
txtSickTime.Text = newTest.PutThisDecimalInTheBox.ToString();
}
}
public class Test
{
public Decimal PutThisDecimalInTheBox;
public Test()
{
PutThisDecimalInTheBox = 320.500m;
}
}
public class DecimalTextBox : System.Windows.Controls.TextBox
{//this is a modified textbox that takes in decimal values also modified to highlight all text on focus
bool alreadyFocused;
private string PreviousText;
string _filterString;
int _dollarPrecision;
int _decimalPrecision;
public string FilterString
{
get { return _filterString; }
set { _filterString = value; }
}
public int DollarPrecision
{
get { return _dollarPrecision; }
set { _dollarPrecision = value; }
}
public int DecimalPrecision
{
get { return _decimalPrecision; }
set { _decimalPrecision = value; }
}
public decimal TextDecimal
{
get { return Convert.ToDecimal(this.Text); }
}
public DecimalTextBox()
{
TextAlignment = System.Windows.TextAlignment.Right;
FontFamily = new System.Windows.Media.FontFamily("Courier New");
FilterString = "-1234567890.";
this.TextChanged += DecimalTextBox_TextChanged;//add the events
}
//event function that limits the input in the text box
private void DecimalTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
this.TextChanged -= DecimalTextBox_TextChanged;//remove the event so it doesn't get called again
//get the cursor location to fix it later
int location = this.SelectionStart;
//don't allow anything except the filter string
if ((!string.IsNullOrEmpty(FilterString)))
{
if (this.Text.Trim().Length > 0)
{
for (int i = 0; i <= this.Text.Length - 1; i++)
{
if (!(this.FilterString.Contains(this.Text.Substring(i, 1))))
{
this.Text = this.Text.Remove(i, 1);
}
}
}
string tempText = Text.Replace("-", "");
string[] splitAtDecimal = tempText.Split('.');
if (splitAtDecimal.Length > 2)
{
Text = PreviousText;
}
else if (splitAtDecimal.Length == 2)
{
if (splitAtDecimal[0].Length > DollarPrecision)//if violating dollar or decimal precision return to previoustext
{
Text = PreviousText;
}
if (splitAtDecimal[1].Length > DecimalPrecision)
{
Text = PreviousText;
}
}
//set the PreviousText=Text for comparison next time textchanged is called
PreviousText = Text;
//this.SelectionStart = this.Text.Length;
this.TextChanged += DecimalTextBox_TextChanged;//add the event back
}
}
}
}
The reason the problem is occurring is because although visual studio displays the value of the decimal as 320.5, when it is converted to a string it retains those 2 trailing zeros.
Thus your string will be 320.500.
The answer to the question in this case would be to either drop the trailing zeros or add +1 to your DecimalTextBox's DecimalPrecision, otherwise it gets reverted to the DecimalTextBox's original value of "".
Personally I believe it should show the trailing zeros if it's going to retain them after the fact.

name does not exist in the namespace of wpf project

summary of soInput.xaml:
xmlns:core="clr-namespace:MyProject.Fun.Core"
xmlns:behave="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
<TextBox Name="txtValue"
Margin="0"
Style="{DynamicResource soTextBox}"
TextWrapping="NoWrap"
Height="50"
Foreground="#FF363636"
FontSize="18.667"
FontWeight="Bold"
Grid.ColumnSpan="2"
IsEnabled="{Binding IsEnabled,ElementName=Input}"
Text="{Binding soValue,ElementName=Input,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"
GotFocus="txtValue_GotFocus"
LostFocus="txtValue_LostFocus">
<behave:Interaction.Behaviors>
<core:TextBoxKeyboardBehavior/>
</behave:Interaction.Behaviors>
</TextBox>
soInput.xaml.cs:
namespace MyProject.Fun
{
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
public partial class soInput : UserControl, IComponentConnector
{
public static readonly DependencyProperty soErrorProperty = DependencyProperty.Register("soError", typeof(string), typeof(soInput));
public static readonly DependencyProperty soHelpDescriptionProperty = DependencyProperty.Register("soHelpDescription", typeof(string), typeof(soInput), new UIPropertyMetadata(""));
public static readonly DependencyProperty soHelpTitleProperty = DependencyProperty.Register("soHelpTitle", typeof(string), typeof(soInput), new UIPropertyMetadata(""));
public static readonly DependencyProperty soLabelProperty = DependencyProperty.Register("soLabel", typeof(string), typeof(soInput));
public static readonly DependencyProperty soValueProperty = DependencyProperty.Register("soValue", typeof(string), typeof(soInput));
public soInput()
{
this.InitializeComponent();
}
private void Input_GotFocus(object sender, RoutedEventArgs e)
{
}
private void txtValue_GotFocus(object sender, RoutedEventArgs e)
{
}
private void txtValue_LostFocus(object sender, RoutedEventArgs e)
{
}
public string soError
{
get
{
return (string) base.GetValue(soErrorProperty);
}
set
{
base.SetValue(soErrorProperty, value);
}
}
public string soHelpDescription
{
get
{
return (string) base.GetValue(soHelpDescriptionProperty);
}
set
{
base.SetValue(soHelpDescriptionProperty, value);
}
}
public string soHelpTitle
{
get
{
return (string) base.GetValue(soHelpTitleProperty);
}
set
{
base.SetValue(soHelpTitleProperty, value);
}
}
public string soLabel
{
get
{
return (string) base.GetValue(soLabelProperty);
}
set
{
base.SetValue(soLabelProperty, value);
}
}
public string soValue
{
get
{
return (string) base.GetValue(soValueProperty);
}
set
{
base.SetValue(soValueProperty, value);
}
}
}
}
TextBoxKeyboardBehavior.cs:
using MyProject.Fun.Helpers;
using System;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Interactivity;
namespace MyProject.Fun.Core
{
public partial class TextBoxKeyboardBehavior : Behavior<TextBox>
{
protected override void OnAttached()
{
base.OnAttached();
base.AssociatedObject.GotFocus += new RoutedEventHandler(this.AssociatedObject_GotFocus);
base.AssociatedObject.LostFocus += new RoutedEventHandler(this.AssociatedObject_LostFocus);
}
private void AssociatedObject_LostFocus(object sender, RoutedEventArgs e)
{
Button button = base.AssociatedObject.Template.FindName("keyboardBtn", base.AssociatedObject) as Button;
if (button != null)
{
button.Click -= new RoutedEventHandler(this.btn_Click);
}
if (button != null)
{
button.Visibility = Visibility.Hidden;
}
}
private void AssociatedObject_GotFocus(object sender, RoutedEventArgs e)
{
Button button = base.AssociatedObject.Template.FindName("keyboardBtn", base.AssociatedObject) as Button;
if (button == null)
{
base.AssociatedObject.ApplyTemplate();
}
button = (base.AssociatedObject.Template.FindName("keyboardBtn", base.AssociatedObject) as Button);
if (button != null)
{
button.Click += new RoutedEventHandler(this.btn_Click);
button.Visibility = Visibility.Visible;
}
}
private void btn_Click(object sender, RoutedEventArgs e)
{
BindingExpression bindingExpression = BindingOperations.GetBindingExpression(base.AssociatedObject, TextBox.TextProperty);
Keyboard keyboard = new Keyboard();
Binding binding = new Binding();
binding.Source = bindingExpression.DataItem;
binding.Path = bindingExpression.ParentBinding.Path;
binding.Mode = bindingExpression.ParentBinding.Mode;
binding.UpdateSourceTrigger = bindingExpression.ParentBinding.UpdateSourceTrigger;
binding.NotifyOnTargetUpdated = bindingExpression.ParentBinding.NotifyOnTargetUpdated;
binding.NotifyOnSourceUpdated = bindingExpression.ParentBinding.NotifyOnSourceUpdated;
binding.NotifyOnValidationError = bindingExpression.ParentBinding.NotifyOnValidationError;
binding.ValidatesOnDataErrors = bindingExpression.ParentBinding.ValidatesOnDataErrors;
keyboard.TextTxt.SetBinding(TextBox.TextProperty, binding);
bool visibility = NavigationHelper.MainLayout.ModalBackground.Visibility != Visibility.Visible;
Util.ShowKeyboardForm(keyboard, visibility);
}
private object GetValue(string path, object dataItem)
{
string[] array = path.Split(new char[]
{
'.'
});
object obj = null;
System.Reflection.PropertyInfo property = dataItem.GetType().GetProperty(path);
object result;
if (property != null)
{
obj = property.GetValue(dataItem, null);
result = obj;
}
else
{
string[] array2 = array;
for (int i = 0; i < array2.Length; i++)
{
string name = array2[i];
if (obj == null)
{
property = dataItem.GetType().GetProperty(name);
obj = property.GetValue(dataItem, null);
}
else
{
property = obj.GetType().GetProperty(name);
obj = property.GetValue(obj, null);
}
}
result = obj;
}
return result;
}
}
}
error:
The name "TextBoxKeyboardBehavior" does not exist in the namespace "clr-namespace:MyProject.Fun.Core".
in backup of project it does work but in this case does not work !!!
all code are in same project and work last night but today does not work !

how add behavior in expression blend

Hi
There is a behavior in following code
I want to use this behavior in my WPF application
But i cant attached this behavior to my project
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using System.ComponentModel;
namespace Brainsiders.MouseOver3D
{
[Description("MouseOver3D - A behavior that applies the MouseOver Design Interaction Pattern to a 3D environment.")]
public class MouseOver3D : TargetedTriggerAction<FrameworkElement>
{
private TimeSpan hoverUp_duration = TimeSpan.FromSeconds(0.5);
[Category("Mouse Over 3D - Going Up")]
public TimeSpan HoverUp_duration
{
get { return hoverUp_duration; }
set { hoverUp_duration = value; }
}
private TimeSpan hoverDown_Duration = TimeSpan.FromSeconds(0.9);
[Category("Mouse Over 3D - Going Down")]
public TimeSpan HoverDown_Duration
{
get { return hoverDown_Duration; }
set { hoverDown_Duration = value; }
}
[Category("Mouse Over 3D - Going Up")]
public IEasingFunction HoverUp_Easing { get; set; }
[Category("Mouse Over 3D - Going Down")]
public IEasingFunction HoverDown_Easing { get; set; }
private double hoverOffset = 30;
[Category("Mouse Over 3D - General")]
public double HoverOffset
{
get { return hoverOffset; }
set { hoverOffset = value; }
}
private FrameworkElement feAssociatedObject;
private FrameworkElement feSourceObject;
private FrameworkElement feTargetObject;
private PlaneProjection ProjectionTargetObject;
private Storyboard SB_HoverZ;
protected override void Invoke(object parameter)
{
FrameworkElement myElement = this.AssociatedObject as FrameworkElement;
}
protected override void OnAttached()
{
base.OnAttached();
feAssociatedObject = (FrameworkElement)this.AssociatedObject;
feSourceObject = (FrameworkElement)this.AssociatedObject;
feSourceObject.Loaded += new RoutedEventHandler(feSourceObject_Loaded);
}
void feSourceObject_Loaded(object sender, RoutedEventArgs e)
{
feSourceObject.Loaded -= new RoutedEventHandler(feSourceObject_Loaded);
ProjectionTargetObject = new PlaneProjection();
feTargetObject = (FrameworkElement)this.TargetObject;
if (feTargetObject == null) feTargetObject = feAssociatedObject;
if (feTargetObject.Projection == null)
{
feTargetObject.RenderTransformOrigin = new Point(0.5, 0.5);
PlaneProjection pj = new PlaneProjection();
feTargetObject.Projection = pj;
}
feSourceObject.MouseEnter += new MouseEventHandler(feSourceObject_MouseEnter);
feSourceObject.MouseLeave += new MouseEventHandler(feSourceObject_MouseLeave);
}
protected override void OnDetaching()
{
base.OnDetaching();
}
void feSourceObject_MouseLeave(object sender, MouseEventArgs e)
{
DeactivateAnimation();
}
void feSourceObject_MouseEnter(object sender, MouseEventArgs e)
{
ActivateAnimation();
}
bool bAnimationActivated = false;
private void ActivateAnimation()
{
if (bAnimationActivated == false)
{
AnimateHoverZ(HoverOffset, true);
bAnimationActivated = true;
}
}
private void DeactivateAnimation()
{
if (bAnimationActivated == true)
{
AnimateHoverZ(0, false);
bAnimationActivated = false;
}
}
private void AnimateHoverZ( Double Z, bool HoverUp)
{
if (HoverUp == true)
playAnimation(feTargetObject, "(UIElement.Projection).(PlaneProjection.LocalOffsetZ)", HoverUp_duration, Z, SB_HoverZ, HoverUp_Easing);
else
playAnimation(feTargetObject, "(UIElement.Projection).(PlaneProjection.LocalOffsetZ)", HoverDown_Duration, Z, SB_HoverZ, HoverDown_Easing);
}
public static void playAnimation(FrameworkElement element, string property, TimeSpan time, double value, Storyboard sb, IEasingFunction EasingFunction)
{
sb = new Storyboard();
sb.Children.Clear();
DoubleAnimation animation = new DoubleAnimation();
animation.Duration = time;
animation.To = value;
animation.EasingFunction = EasingFunction;
Storyboard.SetTargetProperty(animation, new PropertyPath(property));
Storyboard.SetTarget(animation, element);
sb.Children.Add(animation);
sb.Begin();
}
}
}
You need to add the necessary references (System.Windows.Interactivity)
to your project, for that you need to have some version of the Blend SDK installed.
Then to use this in XAML you need to define namespaces for both interactivity and this behavior:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:bs="clr-namespace:Brainsiders.MouseOver3D"
Then you should be able to attach it like this:
<Button>
<i:Interaction.Behaviors>
<bs:MouseOver3D />
</i:Interaction.Behaviors>
</Button>

Text-property of my ASP.NET Composite-control doesn't set text-changes

I have build a composite control which renders a TextControl or a RADEditor control, dependable of a property a set. Both rendered controls have a Text-property. The problem is that when I change the Textvalue on my webpage (when it is running) it won't set the new Text-value but the old Textvalue instead.
Does anyboy know what I'm doing wrong?
Below the code of my composite-control.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Web.UI.HtmlControls;
using Framework.WebControls;
namespace Components.Broadcasting.Controls
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:TextControl runat=server></{0}:TextControl>")]
public class TextControl : CompositeControl, INamingContainer, IDisposable
{
//private Control _myControl;
private Label _myLabel;
private HtmlGenericControl _contentContainer;
private HtmlGenericControl _labelBlock;
private HtmlGenericControl _inputBlock;
public override ControlCollection Controls
{
get
{
EnsureChildControls();
return base.Controls;
}
}
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Text
{
get
{
String s = (String)ViewState["Text"];
return ((s == null) ? String.Empty : s);
}
set
{
ViewState["Text"] = value;
}
}
[Bindable(true)]
[Category("Campagne Broadcasting")]
[DefaultValue("Naam label")]
[Description("Label horende bij het contenttype")]
public string Label
{
get
{
String s = (String)ViewState["label"];
return ((s == null) ? String.Empty : s);
}
set
{
ViewState["label"] = value;
}
}
[Bindable(true)]
[Category("Campagne Broadcasting")]
[DefaultValue(XMLElementType.Heading)]
[Description("Nog in te vullen")]
public XMLElementType XMLElementType
{
get
{
if (ViewState["textContentType"] == null) return XMLElementType.Heading;
return (XMLElementType)ViewState["textContentType"];
}
set
{
ViewState["textContentType"] = value;
}
}
[Bindable(true)]
[Category("Campagne Broadcasting")]
[DefaultValue("0")]
[Description("Layoutposition of the contentitem")]
public int ContentPosition
{
get
{
if (ViewState["contentPosition"] == null) return 0;
return (int)ViewState["contentPosition"];
}
set
{
ViewState["textContentType"] = value;
}
}
[Bindable(true)]
[Category("Campagne Broadcasting")]
[DefaultValue("0")]
[Description("Layoutposition of the contentitem")]
public XmlOutputGroup XMLOutputGroup
{
get
{
if (ViewState["xmlOutputGroup"] == null) return 0;
return (XmlOutputGroup)ViewState["xmlOutputGroup"];
}
set
{
ViewState["xmlOutputGroup"] = value;
}
}
protected override void RecreateChildControls()
{
EnsureChildControls();
}
protected override void CreateChildControls()
{
Controls.Clear();
string containerClass = "contentContainer";
string labelBlock = "labelBlock";
string inputBlock = "inputBlock";
_myLabel = new Label();
_myLabel.Text = Label;
_contentContainer = new HtmlGenericControl("div");
_contentContainer.Attributes["class"] = containerClass;
_labelBlock = new HtmlGenericControl("div");
_labelBlock.Attributes["class"] = labelBlock;
_inputBlock = new HtmlGenericControl("div");
_inputBlock.Attributes["class"] = inputBlock;
_contentContainer = new HtmlGenericControl("div");
_contentContainer.Attributes["class"] = containerClass;
_labelBlock.Controls.Add(_myLabel);
if (XMLElementType == XMLElementType.Heading)
{
TextBox _myControl = new TextBox();
_myControl.Text = this.Text;
_inputBlock.Controls.Add(_myControl);
}
else if (XMLElementType == XMLElementType.Content)
{
RadEditor _myControl = new RadEditor();
_myControl.Content = this.Text;
_inputBlock.Controls.Add(_myControl);
}
else if (XMLElementType == XMLElementType.SlideTypeName)
{
TextBox _myControl = new TextBox();
_myControl.Text = this.Text;
_inputBlock.Controls.Add(_myControl);
}
else if (XMLElementType == XMLElementType.Image)
{
ImageUploader _myControl = new ImageUploader();
_inputBlock.Controls.Add(_myControl);
}
_contentContainer.Controls.Add(_labelBlock);
_contentContainer.Controls.Add(_inputBlock);
this.Controls.Add(_contentContainer);
}
protected override void RenderContents(HtmlTextWriter output)
{
_contentContainer.RenderControl(output);
}
}
}
Thanks in advance
Kind regards, Patrick
You are exposing properties such as Label, Text, but only using them in CreateChildControls - which is too early in the page lifecycle. The easiest way to deal with this is to delegate the property to a child control, as in the example below for the Label property. You could handle the Text property similarly.
Alternatively, you can set the properties on your child controls in your RenderContents override, but this adds some complexity.
public string Label
{
get
{
EnsureChildControls();
return _myLabel.Text;
}
set
{
EnsureChildControls();
_myLabel.Text = value;
}
}

Categories