mvvm how to pass data from one view model to another view model - silverlight

I have One View which has one Data grid with radio Button , onchecking radio Box , the selected row should go to other View Screen Textbox
here is my first ViewModel
public class CampaignSearchResultsViewModel : ViewModelBase
{
public CampaignSearchResultsViewModel(List<Lead> obj)
{
foreach(Lead lead in obj)
{
SelectedLead = lead;
}
}
public CampaignSearchResultsViewModel()
{
this.Commands.Add("CheckedCommand", new ActionCommand<Lead>(CheckIt));
Commands.Add("OutboundSelect", new ActionCommand<Object>(OutboundSelection));
_leads = new ObservableCollection<Lead>();
}
public ICommand OutboundSelect
{
get
{
return Commands["OutboundSelect"];
}
}
public void OutboundSelection(Object obj)
{
}
private void CheckIt(Lead lead)
{
SelectedLead = lead;
LeadViewModel lmv = new LeadViewModel(this);
}
#region Private
private ObservableCollection<Lead> _leads;
public bool IsChecked { get; set; }
private ICommand _checkedCommand;
private object _testProperty;
private Lead _selectedLead;
private ICollectionView icv;
#endregion
private ICommand _checkedRadioCommand;
private bool _inboundChecked;
#region Properties
public ObservableCollection<Lead> Leads
{
get { return _leads; }
set
{
_leads = value;
FirePropertyChanged("Leads");
}
}
public Lead SelectedLead
{
get { return _selectedLead; }
set { _selectedLead = value; }
}
public ICommand CheckedCommand
{
get
{
return Commands["CheckedCommand"];
}
}
public bool InboundChecked
{
get
{
return _inboundChecked;
}
private set
{
if (_inboundChecked != value)
{
_inboundChecked = value;
FirePropertyChanged("InboundChecked");
}
}
}
#endregion
}
i have to map SelectedLead to the other view model i have pass info to SearchCampaignMembers() method , how
public partial class LeadViewModel : ViewModelBase
{
public void SearchCampaignMembers()
{
_service.Load(_service.SearchCampaignMembersQuery(Entity.FirstName, Entity.LastName), lo =>
{
if (!lo.HasError)
{
ListLead = lo.Entities.ToList();
_savedLeadStatusId = Entity.LeadStatusId;
EntitySet = _service.Leads;
if (ListLead.Count == 1)
{
if (Entity != null)
{
IsVendorLead = Entity.LeadTypeId == Lookups.LeadType.VendorLead;
//Lead Update History
EntityQuery<LeadUpdateHistory> historyquery = null;
historyquery = _service.GetLeadUpdateHistoryByLeadIdQuery(Entity.LeadId);
_service.Load(historyquery, l =>
{
if (!l.HasError)
{
EntityHistory = _service.LeadUpdateHistories;
}
}, null);
//Lead Assignment
EntityQuery<LeadsAssignment> assignmentquery = null;
assignmentquery = _service.GetLeadsAssignmentByLeadIdQuery(Entity.LeadId);
_service.Load(assignmentquery, l =>
{
if (!l.HasError)
{
EntityAssignment = _service.LeadsAssignments;
}
}, null);
if (Entity.LeadTypeId == Lookups.LeadType.PhoneLead)
{
IsInboundLead = Entity.VendorId == null;
IsOutboundLead = Entity.VendorId != null;
}
else
{
IsInboundLead = false;
IsOutboundLead = false;
}
//SelectTimeToCall(Entity);
if (IsOutboundLead)
SelectedCampaign = Entity.LeadCampaigns.FirstOrDefault().Campaign;
else
SelectCampaign(Entity);
OperationsListener listener = new OperationsListener();
listener.Completed += (s, args) =>
{
CompleteInitializing();
//SwitchTab(param.InitialTab);
Action action = () =>
{
SelectDealer(Entity);
};
//GetDealerRecommendation(Entity.Address.ZipCode, action);
SelectStatus(Entity);
//if (callback != null)
// callback();
};
LoadLookupData(listener);
listener.Start();
}
}
else if (ListLead.Count >= 1)
{
CampaignSearchResultsViewModel vm = new CampaignSearchResultsViewModel();
foreach (Lead lead in ListLead)
{
vm.Leads.Add(lead);
ObservableCollection<Lead> abc;
abc = new ObservableCollection<Server.DataAccess.Lead>();
}
ViewController.OpenDialog("SearchCampaignResults", vm, r =>
{
});
}
else if (ListLead.Count == 0)
{
ViewController.OpenDialog("NoResults", (r) =>
{
});
}
}
else
{
//if (callback != null)
// callback();
}
}, null);
}
}

If you use MVVM Light Toolkit, see Messenger class see this answer for sample.

Related

How do I set "OnPropertyChanged" on Properties from Model?

I Have Two ComboBoxes for example Country and State where State ComboBox's ItemSource depends on Selected Country of First ComboBox.
Country and State Properties are defined in separate CountryModel(CountryID,CountryName) and StateModel(CountryID,StateID,StateName).
Now there is the Model "UserModel" is like :
public class UserModel:ViewModelBase
{
private string _userName;
public string UserName
{
get { return _userName; }
set { _userName = value; OnPropertyChanged("UserName"); }
}
private long _stateID;
public long StateID
{
get { return _stateID; }
set { _stateID = value; OnPropertyChanged("StateID"); }
}
private int _countryID;
public int CountryID
{
get { return _countryID; }
set { _countryID = value; OnPropertyChanged("CountryID"); }
}
}
It has a Service "UserModelService" for populating :
public class UserModelService
{
public UserModelService()
{
}
public ObservableCollection<UserModel> GetUserList()
{...}
public ObservableCollection<CountryModel> GetCountryList()
{...}
public ObservableCollection<StateModel> GetStateList()
{...}
}
Now The UserViewModel is Like:
public class UserViewModel:ViewModelBase,IPageViewModel
{
UserModelService modelService;
public UserViewModel()
{
modelService = new UserModelService();
GetData();
}
private void GetData()
{
UserList = modelService.GetUserList();
CountryList = modelService.GetCountryList();
StateList = modelService.GetStateList();
}
private UserModel _currentUser=new UserModel();
public UserModel CurrentUser
{
get { return _currentUser; }
set
{
if (value == _currentUser) return;
_currentUser = value; OnPropertyChanged("CurrentUser");
}
}
private ObservableCollection<UserModel> _userList;
public ObservableCollection<UserModel> UserList
{
get { return _userList; }
set
{
if (value == _userList) return;
_userList = value;
OnPropertyChanged("UserList");
}
}
private ObservableCollection<CountryModel> _countryList;
public ObservableCollection<CountryModel> CountryList
{
get { return _countryList; }
set { _countryList = value; OnPropertyChanged("CountryList"); }
}
private ObservableCollection<StateModel> _stateList;
public ObservableCollection<StateModel> StateList
{
get { return _stateList; }
set
{
_stateList = value;
OnPropertyChanged("StateList");
}
}
}
Now the Country and State ComboBox's ItemSource is binded to UserViewModels "CountryList" and "StateList" respectively. In this scenario how to I repopulate StateList OnPropertyChange of CurrentUser.CountryID?
EDIT: I Solved it by introducing separate property for Selected Country and OnPropertyChanged CurrentUser.CountryID=selectedCountry. Thanks
Handle the PropertyChanged event for the current user:
public UserModel CurrentUser
{
get { return _currentUser; }
set
{
if (value == _currentUser)
return;
if (_currentUser != null)
_currentUser.PropertyChanged -= OnCurrentUserPropertyChanged;
_currentUser = value;
if (_currentUser != null)
_currentUser.PropertyChanged += OnCurrentUserPropertyChanged;
OnPropertyChanged("CurrentUser");
}
}
private void OnCurrentUserPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(UserModel.CountryID))
{
UserModel userModel = (UserModel)sender;
var states = ...; //get states by userModel.CountryID
StateList = states;
}
}

.net c# WebChannelFactory keepAliveEnabled=false with webHttpBehavior

I create WebChannelFactory. I need set KeepAlive=false.
I found only one solution use CustomBinding. and set property keepAliveEnabled to false.
I use custom behavior for my factory also.
Code:
static CustomBinding GetBinding(MySettings serviceSettings = null)
{
var customBinding = new CustomBinding();
HttpTransportBindingElement transportBindingElement = new HttpTransportBindingElement();
transportBindingElement.KeepAliveEnabled = false;
transportBindingElement.MaxBufferSize = 0x07000000;
transportBindingElement.MaxReceivedMessageSize = 0x07000000;
if (serviceSettings != null)
{
customBinding.SendTimeout = serviceSettings.SendTimeout;
}
customBinding.Elements.Add(transportBindingElement);
return customBinding;
}
var customBinding = GetBinding(serviceSettings);
WebChannelFactory<TChannel> factory = new WebChannelFactory<TChannel>(customBinding, new Uri(url));
factory.Endpoint.Behaviors.Add(new MyWebHttpBehavior(userId));
class MyWebHttpBehavior : IEndpointBehavior
{
private int _userId;
public MyWebHttpBehavior(int userId)
{
_userId = userId;
}
public void AddBindingParameters(ServiceEndpoint serviceEndpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{ }
public void ApplyClientBehavior(ServiceEndpoint serviceEndpoint, System.ServiceModel.Dispatcher.ClientRuntime behavior)
{
behavior.MessageInspectors.Add(new MyClientMessageInspector(_userId));
}
public void ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
{ }
public void Validate(ServiceEndpoint serviceEndpoint)
{ }
}
In current situation i get error "does not have a Binding with the None MessageVersion".

Telerik RadPropertyGrid Content of CollectionEditorPicker

as the topic suggests I wan't to modify the Content of the CollectionEditorPicker. This control is used to open the floating Window for the List of nested Properties.
Unfortunally the RadPropertyGrid don't show any Information about the collection in the Field.
How can I set some value in there? For example a placeholder like "Click here to open the collection" or "xx Items" or "Item 1, Item 2, Item 3..." so see some preview or Information about the field.
I've tried it with a template Selector, but if I'm doing so, the opened Popup is not resizable anymore. Also it looses some Information which are in the default CollectionEditorPicker.
Can you help me?
Below a minimal working Example.
The XAML:
<Window x:Class="TelerikPropertyGridTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation"
xmlns:model="clr-namespace:TelerikPropertyGridTest.Model"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
<model:TemplateSelector x:Key="RadPropertyListTemplateSelector">
<!-- Not Working -->
<model:TemplateSelector.CollectionsDataTemplate>
<DataTemplate>
<telerik:RadDropDownButton Content="Test">
<telerik:RadDropDownButton.DropDownContent>
<telerik:CollectionEditor telerik:AutoBindBehavior.UpdateBindingOnElementLoaded="Source"
></telerik:CollectionEditor>
</telerik:RadDropDownButton.DropDownContent>
</telerik:RadDropDownButton>
</DataTemplate>
</model:TemplateSelector.CollectionsDataTemplate>
<model:TemplateSelector.FloatNumberTemplate>
<DataTemplate>
<telerik:RadNumericUpDown telerik:AutoBindBehavior.UpdateBindingOnElementLoaded="Value" />
</DataTemplate>
</model:TemplateSelector.FloatNumberTemplate>
<model:TemplateSelector.IntNumberTemplate>
<DataTemplate>
<telerik:RadNumericUpDown telerik:AutoBindBehavior.UpdateBindingOnElementLoaded="Value"
NumberDecimalDigits="0" />
</DataTemplate>
</model:TemplateSelector.IntNumberTemplate>
</model:TemplateSelector>
</Grid.Resources>
<telerik:RadPropertyGrid Item="{Binding ObjectToBind}"
AutoGeneratingPropertyDefinition="RadPropertyGrid_OnAutoGeneratingPropertyDefinition"
EditorTemplateSelector="{StaticResource RadPropertyListTemplateSelector}">
</telerik:RadPropertyGrid>
</Grid>
</Window>
The ViewModel (generates a Random Object for testing)
public class MainWindowViewModel : BindableBase
{
private readonly Random _random = new Random();
private IExampleInterface _objectToBind;
public MainWindowViewModel()
{
this.ObjectToBind = new ExampleImplementation
{
SomeBooleanValue = this._random.Next() % 2 == 1,
SomeDateValue = this.RandomDay(),
SomeIntValue = this._random.Next(),
SomeString = Guid.NewGuid().ToString(),
SubClasses = new List<IExampleInterface>
{
new ExampleImplementation
{
SomeBooleanValue = this._random.Next() % 2 == 1,
SomeDateValue = this.RandomDay(),
SomeIntValue = this._random.Next(),
SomeString = Guid.NewGuid().ToString(),
SubClasses = new List<IExampleInterface>
{
new ExampleImplementation
{
SomeBooleanValue =
this._random.Next() % 2 == 1,
SomeDateValue = this.RandomDay(),
SomeIntValue = this._random.Next(),
SomeString = Guid.NewGuid().ToString()
}
}
}
}
};
}
public IExampleInterface ObjectToBind
{
get { return this._objectToBind; }
set
{
if (this._objectToBind != value)
{
this._objectToBind = value;
this.OnPropertyChanged("ObjectToBind");
}
}
}
private DateTime RandomDay()
{
var start = new DateTime(1995, 1, 1);
var range = (DateTime.Today - start).Days;
return start.AddDays(this._random.Next(range));
}
}
The IExampleInterface (should be later on a real Interface):
public interface IExampleInterface
{
string SomeString { get; set; }
int SomeIntValue { get; set; }
double SomeDouble { get; set; }
IList<IExampleInterface> SubClasses { get; set; }
IList<IExampleInterface> SubClasses2 { get; set; }
bool SomeBooleanValue { get; set; }
DateTime SomeDateValue { get; set; }
SomeEnum SomeEnumValue { get; set; }
}
The ExampleImplementation (should have later on a Real Implementation with additional Properties).
public class ExampleImplementation : BindableBase, IExampleInterface
{
private bool _someBooleanValue;
private DateTime _someDateValue;
private double _someDouble;
private SomeEnum _someEnumValue;
private int _someIntValue;
private string _someString;
private ObservableCollection<IExampleInterface> _subClasses;
private ObservableCollection<IExampleInterface> _subClasses2;
public bool SomeBooleanValue
{
get { return this._someBooleanValue; }
set
{
if (this._someBooleanValue != value)
{
this._someBooleanValue = value;
this.OnPropertyChanged("SomeBooleanValue");
}
}
}
public DateTime SomeDateValue
{
get { return this._someDateValue; }
set
{
if (this._someDateValue != value)
{
this._someDateValue = value;
this.OnPropertyChanged("SomeDateValue");
}
}
}
public double SomeDouble
{
get { return this._someDouble; }
set
{
if (Math.Abs(this._someDouble - value) > 0.01)
{
this._someDouble = value;
this.OnPropertyChanged("SomeDouble");
}
}
}
public SomeEnum SomeEnumValue
{
get { return this._someEnumValue; }
set
{
if (this._someEnumValue != value)
{
this._someEnumValue = value;
this.OnPropertyChanged("SomeEnumValue");
}
}
}
public int SomeIntValue
{
get { return this._someIntValue; }
set
{
if (this._someIntValue != value)
{
this._someIntValue = value;
this.OnPropertyChanged("SomeIntValue");
}
}
}
[Display(Name = #"TestString", GroupName = #"TestGroup", Description = #"TestDescription")]
public string SomeString
{
get { return this._someString; }
set
{
if (this._someString != value)
{
this._someString = value;
this.OnPropertyChanged("SomeString");
}
}
}
[Display(Name = #"Some Subclasses")]
public IList<IExampleInterface> SubClasses
{
get { return this._subClasses; }
set
{
if (!Equals(this._subClasses, value))
{
this._subClasses = new ObservableCollection<IExampleInterface>(value);
this.OnPropertyChanged("SubClasses");
}
}
}
public IList<IExampleInterface> SubClasses2
{
get { return this._subClasses2; }
set
{
if (!Equals(this._subClasses2, value))
{
this._subClasses2 = new ObservableCollection<IExampleInterface>(value);
this.OnPropertyChanged("SubClasses2");
}
}
}
}
And finally the TemplateSelector
public class TemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
var def = item as PropertyDefinition;
if (def == null || def.SourceProperty == null)
{
return base.SelectTemplate(item, container);
}
if (typeof (IEnumerable).IsAssignableFrom(def.SourceProperty.PropertyType) && typeof(string) != def.SourceProperty.PropertyType)
{
return this.CollectionsDataTemplate;
}
if (typeof (double).IsAssignableFrom(def.SourceProperty.PropertyType))
{
return this.FloatNumberTemplate;
}
if (typeof (int).IsAssignableFrom(def.SourceProperty.PropertyType))
{
return this.IntNumberTemplate;
}
return base.SelectTemplate(item, container);
}
public DataTemplate CollectionsDataTemplate { get; set; }
public DataTemplate FloatNumberTemplate { get; set; }
public DataTemplate IntNumberTemplate { get; set; }
}
This is what I expect
The optimal solution would be to get detailed Information in the TextBlock, like Item 1, item 2 etc.
Thank you.
// Edit:
I've figured out the NullReferenceException and got a Demo to work, so that I can modify the text. But the popup is different to the default. Have you an idea to fix it?
I've updated the text and the example.
After wasting a few hours now I figured out a solution to realize this.
I've added a custom behavior to the Collection template. This behavior sets the Header of the CollectionEditor as soon as it's loaded or updated.
Below you can see my modifications:
The Template:
<model:TemplateSelector.CollectionsDataTemplate>
<DataTemplate>
<telerik:RadDropDownButton Content="Click to edit the collection">
<telerik:RadDropDownButton.DropDownContent>
<telerik:CollectionEditor telerik:AutoBindBehavior.UpdateBindingOnElementLoaded="Source"
ResizeGripperVisibility="Visible">
<i:Interaction.Behaviors>
<model:CollectionEditorBehavior />
</i:Interaction.Behaviors>
</telerik:CollectionEditor>
</telerik:RadDropDownButton.DropDownContent>
</telerik:RadDropDownButton>
</DataTemplate>
</model:TemplateSelector.CollectionsDataTemplate>
The behavior:
internal class CollectionEditorBehavior : Behavior<CollectionEditor>
{
protected override void OnAttached()
{
this.AssociatedObject.SourceUpdated += (sender, args) => this.PrepareHeader();
this.AssociatedObject.DataContextChanged += (sender, args) => this.PrepareHeader();
this.AssociatedObject.Loaded += (sender, args) => this.PrepareHeader();
}
private void PrepareHeader()
{
if (this.AssociatedObject == null)
{
// Error Case
return;
}
if (this.AssociatedObject.CollectionView == null ||
this.AssociatedObject.CollectionView.SourceCollection == null)
{
// Source not set
this.AssociatedObject.Header = "Collection";
return;
}
// Get the property from the DataContext to retrieve HeaderInformation
var propInfo = this.AssociatedObject.DataContext
.GetType()
.GetProperties()
.FirstOrDefault(
propertyInfo =>
Equals(propertyInfo.GetValue(this.AssociatedObject.DataContext),
this.AssociatedObject.CollectionView.SourceCollection));
if (propInfo == null)
{
// We didn't got the property Information, using default value
this.AssociatedObject.Header = "Collection";
return;
}
// Getting the DisplayName Attribute
var attr = Attribute.GetCustomAttribute(propInfo,
typeof (DisplayNameAttribute)) as DisplayNameAttribute;
if (attr != null)
{
// We have a DisplayName attribute
this.AssociatedObject.Header = attr.DisplayName;
return;
}
// Alternative: Get the Display Attribute
var attr2 = Attribute.GetCustomAttribute(propInfo,
typeof (DisplayAttribute)) as DisplayAttribute;
if (attr2 != null)
{
// We have the Display Attribute
this.AssociatedObject.Header = attr2.Name;
return;
}
// We have no DisplayAttribute and no DisplayName attribute, set it to the PropertyName
this.AssociatedObject.Header = propInfo.Name;
}
}

Cross threading exception accessing viewmodel property set from code behind

I have a WPF MVVM app that displays drug information in a telerik grid view. I want to do some filtering and paging in the view model but I keep getting cross-thread exceptions. The initial load works fine. I can change pages/page size without a problem. When I filter the grid, I create an IEnumerable of FilterDescriptors in the code behind and then set it on the Filters property of the view model. At this point, I get the cross-thread exception when doing the query using the filters. I have tried everything I can think of but can't get it to work.
public partial class DrugEdit : Page
{
public DrugEdit()
{
InitializeComponent();
}
private void RadGridView1_Filtered(object sender, Telerik.Windows.Controls.GridView.GridViewFilteredEventArgs e)
{
DrugEditViewModel vm = this.DataContext as DrugEditViewModel;
Telerik.Windows.Controls.RadGridView gv = sender as Telerik.Windows.Controls.RadGridView;
if (gv.FilterDescriptors == null || gv.FilterDescriptors.Count == 0)
vm.Filters = null;
else
{
List<FilterDescriptor> filters = (vm.Filters==null? new List<FilterDescriptor>(): vm.Filters.ToList());
foreach (FilterDescriptor r in e.Removed)
{
var fnd = filters.FirstOrDefault(x => x.Member == r.Member);
if (fnd == null) continue;
filters.Remove(fnd);
}
foreach (FilterDescriptor a in e.Added)
{
var fnd = filters.FirstOrDefault(x => x.Member == a.Member);
if (fnd == null)
{
filters.Add(new FilterDescriptor(a.Member, a.Operator, a.Value, false, a.MemberType));
}
else
{
fnd.Operator = a.Operator;
fnd.Value = a.Value;
}
}
vm.Filters = filters;
}
}
}
public class DrugEditViewModel
: ViewModelBase
{
private Data.DBContext ctx = new Data.DBContext();
private List<FilterDescriptor> FiltersValue = new List<FilterDescriptor>();
public List<FilterDescriptor> Filters
{
get { return FiltersValue; }
set
{
SetPropertyValue((() => Filters), ref FiltersValue, value);
RecordCount = 0;
LoadData();
}
}
private int PageValue = 0;
public int Page
{
get { return PageValue; }
set
{
SetPropertyValue((() => Page), ref PageValue, value);
LoadData();
}
}
private int PageSizeValue = 20;
public int PageSize
{
get { return PageSizeValue; }
set
{
SetPropertyValue((() => PageSize), ref PageSizeValue, value);
Page = 0;
}
}
private int RecordCountValue;
public int RecordCount
{
get { return RecordCountValue; }
set
{
SetPropertyValue((() => RecordCount), ref RecordCountValue, value);
}
}
private ObservableCollection<Models.Drug> DrugsValue;
public ObservableCollection<Models.Drug> Drugs
{
get { return DrugsValue; }
set
{
SetPropertyValue((() => Drugs), ref DrugsValue, value);
}
}
#endregion
#region Methods
private void LoadData()
{
if (ctx == null)
ctx = new Data.DBContext();
//load record count if we don't have it.
if (RecordCount == 0)
{
IsBusy = true;
Task.Run(() =>
{
if (Filters == null || Filters.Count() == 0)
{
RecordCount = ctx.Set<Entities.Drug>().Count();
}
else
{
RecordCount = ctx.Set<Entities.Drug>().Where(Filters).Count();
}
IsBusy = false;
LoadData();
});
return;
}
IsBusy = true;
Task.Run(() =>
{
if (Filters == null || Filters.Count() == 0)
currentPage = (from d in ctx.Query<Entities.Drug>()
orderby d.NDC
select d)
.Skip(PageSize * Page)
.Take(PageSize).ToList();
else
currentPage = (from d in ctx.Query<Entities.Drug>()
orderby d.NDC
select d)
.Where(Filters)
.Skip(PageSize * Page)
.Take(PageSize)
.ToIList() as List<Entities.Drug>;
Drugs = new ObservableCollection<Models.Drug>((from c in currentPage
select new Models.Drug(c)));
IsBusy = false;
});
}
#endregion
}

How can i manage changed value text by highlighting the edited text only?

My question might seems to be duplicate although it is not the same issue i had experienced before.
I have successfully added a richtexbox column to the datagridview as it has being my problem for a while. now you can add richtextbox to the datagridview.
Now am trying to highlight the edited text only but am not setting it work as after i edited the text it highlight the whole text.
for an example from what i wanna get
"Test" = Testing
from the example i above, i only want to highlight the only added one from the existing one.
the code below highlighted the whole text from the datagridview richtextbox cell which is not what i want.
code that am using for color change
private void Gridview_Output_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
Gridview_Output.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = Color.Red;
}
}
Richtextbox class
public partial class RichTextBoxControl : DataGridViewColumn
{
public RichTextBoxControl(): base()
{
base.CellTemplate = new RichTextboxCell1();
}
public override DataGridViewCell CellTemplate
{
get
{
return base.CellTemplate;
}
set
{
if (!((value == null)) && !(value.GetType().IsAssignableFrom(typeof(RichTextboxCell1))))
{
throw new InvalidCastException("Must be a CalendarCell");
}
base.CellTemplate = value;
}
}
}
public class RichTextboxCell1 : DataGridViewTextBoxCell
{
public RichTextboxCell1()
{
}
public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
{
base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);
RichTextBoxEditingControl1 ctl = (RichTextBoxEditingControl1)DataGridView.EditingControl;
if (this.RowIndex >= 0)
{
if ((!object.ReferenceEquals(this.Value, DBNull.Value)))
{
if (this.Value != null)
{
if (this.Value != string.Empty)
{
try
{
ctl.Text =this.Value.ToString();
}
catch (Exception ex)
{
}
}
}
}
}
}
public override System.Type EditType
{
get
{
return typeof(RichTextBoxEditingControl1);
}
}
public override System.Type ValueType
{
get
{
return typeof(String);
}
}
public override object DefaultNewRowValue
{
get
{
return String.Empty;
}
}
}
class RichTextBoxEditingControl1 : RichTextBox, IDataGridViewEditingControl
{
private DataGridView dataGridViewControl;
private bool valueIsChanged = false;
private int rowIndexNum;
public RichTextBoxEditingControl1()
{
}
public object EditingControlFormattedValue
{
get
{
return this.Text;
}
set
{
if (value is string)
{
this.Text = value.ToString();
}
}
}
public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
{
return this.Text;
}
public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
{
this.Font = dataGridViewCellStyle.Font;
this.ForeColor = dataGridViewCellStyle.ForeColor;
this.BackColor = dataGridViewCellStyle.BackColor;
}
public int EditingControlRowIndex
{
get
{
return rowIndexNum;
}
set
{
rowIndexNum = value;
}
}
public bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey)
{
if (Keys.KeyCode == Keys.Left || Keys.KeyCode == Keys.Up || Keys.KeyCode == Keys.Down || Keys.KeyCode == Keys.Right || Keys.KeyCode == Keys.Home || Keys.KeyCode == Keys.End || Keys.KeyCode == Keys.PageDown || Keys.KeyCode == Keys.PageUp)
{
return true;
}
else
{
return false;
}
}
public void PrepareEditingControlForEdit(bool selectAll)
{
}
public bool RepositionEditingControlOnValueChange
{
get
{
return false;
}
}
public DataGridView EditingControlDataGridView
{
get
{
return dataGridViewControl;
}
set
{
dataGridViewControl = value;
}
}
public bool EditingControlValueChanged
{
get
{
return valueIsChanged;
}
set
{
valueIsChanged = value;
}
}
public Cursor EditingControlCursor
{
get
{
return base.Cursor;
}
}
protected override void OnTextChanged(System.EventArgs eventargs)
{
valueIsChanged = true;
this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
base.OnTextChanged(eventargs);
}
#region IDataGridViewEditingControl Members
Cursor IDataGridViewEditingControl.EditingPanelCursor
{
get { return base.Cursor; }
}
#endregion
}

Resources