Я создал класс, который сокращает текст, который вставляется в текстовое поле, а также добавляет «...».Создайте свойство из класса
Пример:
[ThisTextis]toolong > [ThisTex...]
Я использую Microsoft Visual Studio 2013 на Windows, 8.1 VM (Virtual Machine) и программное обеспечение является App.
Теперь это может быть не идеально, но это работает отлично и прекрасно. То, что я хочу знать сейчас, если я могу создать логическое свойство из этого класса, так что пользователь может включить/отключить его в текстовом поле в XAML:
<TextBox CutText="True"/>
Проблема заключается в том, что я уже использую пре- существующее свойство Text
внутри класса, и мой код не так красив, как я хочу. В любом случае, я был бы очень рад за любые советы и/или помощь.
Edit: Проще говоря, я хочу, чтобы создать TextBlock.TextTrimming
свойство для TextBox
, так как уже существующая собственность ограничивается TextBlock
.
Вот Класс:
class CutText
{
//Create a new instance of a textbox
TextBox textCut = new TextBox();
//Reset at start
public void ResetText(TextBox text)
{
//Overwrite textCut with the chosen TextBox
textCut = text;
//Handles the possibility of already filled textbox
if (textCut.Text != "" || textCut.Text != null)
{
_text = textCut.Text;
}
//Prevents text from being 'Null'
else
{
_text = "";
}
}
//Cuts text to width of textbox
private string CutTextToWidth(string text, double fontSize, double width)
{
//boolean to check if width of text is correct
bool validArea = false;
//comply with difference in width of characters
double CharDiffLength = (stringWidth("M", fontSize) - stringWidth("|", fontSize));
//shortened text
string shortText = text;
//last length which was too long
int LastLongLen = text.Length;
//last length which fit into textbox
int LastFitLen = 0;
if (stringWidth(text, fontSize) < width)
{
shortText = text;
}
else
{
//repeat until the text fits into the appointed area
while (!validArea)
{
if (width < stringWidth(shortText, fontSize))
{
//text is still too long
LastLongLen = shortText.Length;
}
else
{
//text is not too long
LastFitLen = shortText.Length;
}
int newLen = (LastFitLen + LastLongLen)/2;
if (shortText.Length != newLen)
{
//set shortened text
shortText = text.Substring(0, newLen) + "\u2026";
}
validArea = ((width - 10 < stringWidth(shortText, fontSize)) && (stringWidth(shortText, fontSize) < width));
}
}
//return the shortened text
return shortText;
}
//Calculate the width of the text
private double stringWidth(string s, double fontSize)
{
if (s == " ")
s = "\u00a0";
TextBlock t = new TextBlock()
{
FontSize = fontSize,
Text = s
};
t.Measure(new Size(double.MaxValue, double.MaxValue));
return t.ActualWidth;
}
//(GotFocus) Replaces cut text with full text and places the cursor at the chosen position
public void GotFocusText()
{
int index = textCut.SelectionStart;
textCut.Text = _text;
textCut.SelectionStart = index;
}
//(LostFocus) Saves cut text into property/empties the textbox if nothing has been written and sets tooltip
public void LostFocusText()
{
if (!string.IsNullOrWhiteSpace(textCut.Text))
{
Text = textCut.Text;
}
else
{
Text = "";
}
ToolTipService.SetToolTip(textCut, _text);
}
//TextBox.Text Property
private string _text;
public string Text
{
get { return _text; }
set
{
_text = value;
//Receive text, fontsize and width of textbox
textCut.Text = CutTextToWidth(_text, textCut.FontSize, textCut.Width - 25);
}
}
}
Это не совсем так ясно, чего вы пытаетесь достичь. Что вы хотите, дайте последовательность операций. –
@JamesHarcourt Ну, просто поставьте, я хочу создать свойство, подобное свойству 'TextBlock.TextTrimming', но для TextBox, а не для TextBlock. – user3701907